Catalyst-Plugin-I18N-Request
view release on metacpan or search on metacpan
lib/Catalyst/Plugin/I18N/Request.pm view on Meta::CPAN
A very similar behaviour applies to parameter names within the query
string. The keys for these delocalizations begin with
'PARAMETER_delocalize_' instead of 'PATH_delocalize_'.
=head1 LOCALIZATION
Localization involves taking paths and parameter names and replacing
them with values which make more sense to users speaking the requested
language. In the above example, 'search' may not look intuitive to
German users. Out of the box, this plugin allows you to localize these
values transparently via the standard $c->uri_for and
$c->request->uri_with methods which are already standard features of
the Catalyst framework.
Like delocalization, this functionality depends upon the $c->localize
method. However, PATH_delocalize_ is replaced with PATH_localize and
PARAMETER_delocalize_ is replaced with PARAMETER_localize_.
Key | Localized text | Language
==========================================================
PATH_localize_search | recherche | French
PATH_localize_search | suche | German
=head1 METHODS
=head2 setup ( )
Allows Catalyst::Request to localize the results of calls to uri_with.
=cut
sub setup {
my $self = shift;
$self->next::method( @_ );
no strict 'refs';
no warnings 'redefine';
my $uri_with = \&Catalyst::Request::uri_with;
*Catalyst::Request::uri_with = sub {
my ($request) = @_;
my $uri = $uri_with->( @_ );
return $request->{_context}->localize_uri( $uri );
};
}
=head2 prepare ( )
Overrides Catalyst's C<prepare> method to push the context object to the request
object.
=cut
sub prepare {
my $c = shift;
$c = $c->next::method( @_ );
unless( $c->request->{ _context } ) {
Scalar::Util::weaken( $c->request->{ _context } = $c );
}
return $c;
}
=head2 uri_for ( $path [, @args ] [, \%query_values ] )
Calls the native uri_for, but proceeds to localize the resulting path
and query values.
=cut
sub uri_for {
my $c = shift;
$c->localize_uri( $c->next::method( @_ ) );
}
=head2 localize_uri ( $uri )
Localizes a URI using the current context.
=cut
sub localize_uri {
my ($c, $uri) = @_;
return undef unless defined $uri;
$uri = URI->new( $uri ) unless Scalar::Util::blessed( $uri );
# parameters
my $query_form = $uri->query_form_hash;
# decode all strings for character logic rather than byte logic
for my $value ( values %$query_form ) {
for ( ref $value eq 'ARRAY' ? @$value : $value ) {
$_ = "$_";
utf8::decode( $_ );
}
}
# localize the parameters
my $parameters = $c->localize_parameters( $query_form );
# encode all strings for byte logic rather than character logic
for my $value ( values %$parameters ) {
for ( ref $value eq 'ARRAY' ? @$value : $value ) {
$_ = "$_";
utf8::encode( $_ );
}
}
$uri->query_form_hash( $parameters );
# path
$uri->path( $c->localize_path( $uri->path ) );
return $uri;
}
=head2 localize_path ( $path )
( run in 1.838 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )