HTML::MasonでEUC-JPのソースを書きながらUTFで出力

| コメント(0) | トラックバック(0)



HTML::MasonでUTFのデータを使う事が多いので、やっぱりソースファイル(Masonで処理するファイル)もUTFで書きたい(そうじゃないとあちこちでencode()/decode()しなくちゃいけない)。でもエディタやターミナルは基本的にEUC-JPのものを愛用している。環境が全てEUCなのでいまさらUTF対応するのも面倒くさいので、最近は新規プロジェクトを立ち上げる度にこんなハックしてる:



package Projct::App::ApacheHandler;
use strict;

sub handler : method
{
my $class = shift;
my $r = shift;

my $ah = $class->create_ah($r);
return $ah->handle_request($r);
}

sub create_ah
{
my $class = shift;
my $r = shift;

my $comp_root = "...";
my $data_dir = "...";

return HTML::Mason::ApacheHandler->new(
args_method => 'mod_perl', # mod_perlマンセー
comp_root => $comp_root,
data_dir => $data_dir,
resolver_class => 'Project::App::ApacheHandler::Resolver',
$r
);
}
}


ここでHTML::Mason::ApacheHandlerを作るわけだけど、ポイントはResolverを乗っ取る事。これをした上でどこかでResolverを定義する:



package Project::App::ApacheHandler::Resolver;
use strict;
use base qw(HTML::Mason::Resolver::File);
use Encode();
use HTML::Mason::Tools qw(read_file_ref);

sub get_info
{
my ($self, $path, $comp_root_key, $comp_root_path) = @_;

my $srcfile = File::Spec->canonpath( File::Spec->catfile( $comp_root_path, $path ) );
return unless -f $srcfile;
my $modified = (stat _)[9];
my $base = $comp_root_key eq 'MAIN' ? '' : "/$comp_root_key";
$comp_root_key = undef if $comp_root_key eq 'MAIN';

return
HTML::Mason::ComponentSource->new
( friendly_name => $srcfile,
comp_id => "$base$path",
last_modified => $modified,
comp_path => $path,
comp_class => 'HTML::Mason::Component::FileBased',
extra => { comp_root => $comp_root_key },
source_callback => sub {
my $s = read_file_ref($srcfile);
$$s = Encode::decode('euc-jp', $$s);
return $s;
}
);
}


Voila!これでソースファイルはEUCで書いても、実際にはUTF8のMasonオブジェクトファイルができるので、DB内のデータがUTFでもencode()/decode()しないで普通にMasonコードをかける。ちなみに上記はMason1.31でしか動かない。


Author

Daisuke Maki (a.k.a lestrrat): Perl hacker, Director of Japan Perl Association, YAPC::Asia Tokyo Organizer (2009-2012), Fluent in Japanese, English. Ex-Brazilian (sorta)

#perl #c #ruby #java #mysql #english #japanese #opensource #stf #cooking #scotch #cigar


このエントリーをはてなブックマ
ークに追加

翔泳社よりモダンPerl入門(2010)を出版させていただいております。できれば内容をアップデートしたいので是非皆様・・・現在の在庫処理にお力をお貸しください!><

月別アーカイブ