diff options
author | franck cuny <franck@lumberjaph.net> | 2010-05-27 20:36:11 +0200 |
---|---|---|
committer | franck cuny <franck@lumberjaph.net> | 2010-05-27 20:36:11 +0200 |
commit | c8601d93f056efcc018587a6c79cde2f61aeb224 (patch) | |
tree | 3e04478f483f5aff3f62140bd627a1ed7b437f2a | |
parent | initial commit (diff) | |
download | plack-middleware-i18n-c8601d93f056efcc018587a6c79cde2f61aeb224.tar.gz |
detect locale from http headers
-rw-r--r-- | lib/Plack/Middleware/i18n.pm | 44 | ||||
-rw-r--r-- | t/01_basic.t | 15 |
2 files changed, 39 insertions, 20 deletions
diff --git a/lib/Plack/Middleware/i18n.pm b/lib/Plack/Middleware/i18n.pm index 28d4536..6a6e927 100644 --- a/lib/Plack/Middleware/i18n.pm +++ b/lib/Plack/Middleware/i18n.pm @@ -2,8 +2,10 @@ package Plack::Middleware::i18n; use strict; use warnings; + use Plack::Util; use Plack::Util::Accessor qw/default_lang/; +use Plack::Request; use I18N::LangTags; use I18N::LangTags::Detect; @@ -12,23 +14,35 @@ our $VERSION = '0.01'; use parent 'Plack::Middleware'; sub call { - my $self = shift; - my $res = $self->app->(@_); - - my $h = Plack::Util::headers($res->[1]); - - my @languages = ($self->default_lang) if $self->default_lang; - push @languages, - I18N::LangTags::implicate_supers( - I18N::LangTags::Detect->http_accept_langs($h->get('Accept-Language'))); - - # XXX store languages in psgix.languages - # XXX if session, store in session too - # XXX maybe redirect to appropriate location ? - - return $res; + my ($self, $env) = @_; + + my $locale; + + if (my $lang = $env->{'HTTP_ACCEPT_LANGUAGE'}) { + $locale = ( + split( + '-', + ( I18N::LangTags::implicate_supers( + I18N::LangTags::Detect->http_accept_langs($lang) + ) + )[0] + ) + )[0]; + } + else { + $locale = $self->default_lang // 'en'; + } + + $env->{'psgix.locale'} = $locale; + + if (my $session = $env->{'psgix.session'}) { + $session->{locale} = $locale; + } + + $self->app->($env); } + 1; __END__ diff --git a/t/01_basic.t b/t/01_basic.t index 630bd55..c18f862 100644 --- a/t/01_basic.t +++ b/t/01_basic.t @@ -8,20 +8,25 @@ use HTTP::Request::Common; my $handler = builder { enable "i18n"; sub { - [ '200', ['Content-Type' => 'text/html', 'Accept-Language' => 'fr'], - ['Hello world'] + my $env = shift; + [ '200', + ['Content-Type' => 'text/html',], + ['locale is ' . $env->{'psgix.locale'}] ]; }; }; test_psgi - app => $handler, - client => sub { + app => $handler, + client => sub { my $cb = shift; { my $req = GET "http://localhost/"; + $req->header('Accept-Language' => 'fr-FR,de;q=0.8'); ok my $res = $cb->($req); + is $res->content, 'locale is fr'; } -}; + }; done_testing(); + |