Proposal: specifing default encoding of input templates

Posted on 2006-04-21 07:52:49-07 by banb
Proposal: specifing default encoding of input templates
I'm very impressed with this module, especially the section 'DIFFERNCE WITH OTHER WAYS' of pod. But I think it is better that we can specify the default encoding instead of 'utf-8', because (for example) most of current web designers in Japan prefer 'Shift_JIS' (or cp932) to 'UTF-8'. Coaching them to use '[% USE encoding 'shift-jis' %]' directive everywhere is also painful, isn't it ? :)

So I wrote the patch below. Of course I could write new module which was inheritance of T::P::Encoding, but I didn't because hard-coding 'utf-8' in original code seemed not so good.

There are two important points in this patch.
1. You can denote the desired encoding with 'DEFAULT_ENCODING' option in constructor.
2. Encoding detection mechanism now became the outer method 'detect_encoding()'. It makes easier to extend this module, for example, auto-encoding-detection collaborating with Encode::Guess.

This patch might not match the philosophy of T::P::Encoding, so I want any comments.
--- lib/Template/Provider/Encoding.pm.orig 2006-04-21 15:50:35.000000000 +0900 +++ lib/Template/Provider/Encoding.pm 2006-04-21 15:58:42.000000000 +0900 @@ -6,19 +6,35 @@ use base qw( Template::Provider ); use Encode; +sub _init { + my ($self, $params) = @_; + + $self = $self->SUPER::_init($params); + $self->{DEFAULT_ENCODING} = $params->{DEFAULT_ENCODING} || 'utf8'; + $self->{ENCODE_CHECK} = $params->{ENCODE_CHECK} || Encode::FB_DEFAULT; + return $self; +} + sub _load { my $self = shift; my($data, $error) = $self->SUPER::_load(@_); unless (Encode::is_utf8($data->{text})) { - my $encoding = $data->{text} =~ /^\[% USE encoding '([\w\-]+)'/ - ? $1 : 'utf-8'; - $data->{text} = Encode::decode($encoding, $data->{text}); + my $decoder = $self->detect_encoding($data); + $data->{text} = $decoder->decode($data->{text}, $self->{ENCODE_CHECK}); } return ($data, $error); } +sub detect_encoding { + my ($self, $data) = @_; + + my $encoding = $data->{text} =~ /^\[% USE encoding '([\w\-]+)'/ + ? $1 : $self->{DEFAULT_ENCODING}; + return Encode::find_encoding($encoding); +} + 1; __END__
Direct Responses: Write a response