File Coverage

blib/lib/Dancer2/Plugin/Locale.pm
Criterion Covered Total %
statement 59 84 70.2
branch 4 20 20.0
condition 1 5 20.0
subroutine 15 17 88.2
pod 1 2 50.0
total 80 128 62.5


line stmt bran cond sub pod time code
1             package Dancer2::Plugin::Locale;
2              
3 1     1   906328 use strict;
  1         3  
  1         27  
4 1     1   5 use warnings;
  1         3  
  1         28  
5              
6 1     1   958 use Dancer2::Plugin;
  1         12475  
  1         11  
7             $Dancer2::Plugin::Locale::VERSION = '0.07';
8              
9             package Dancer2::Plugin::Locale::Obj;
10 1     1   4307 use Locales 0.33 unicode => 1;
  1         8085  
  1         12  
11 1     1   791 use Locale::Maketext::Utils;
  1         20358  
  1         46  
12 1     1   12 use base 'Locale::Maketext::Utils';
  1         2  
  1         108  
13             our %Lexicon;
14              
15             package Dancer2::Plugin::Locale;
16              
17 1     1   7 use File::Spec;
  1         3  
  1         245  
18              
19             # use Tie::Hash::ReadonlyStack;
20              
21             plugin_keywords 'locale';
22              
23             sub locale {
24 19     19 1 237902 my $dsl = shift;
25              
26 19 100       123 if (@_) {
27 8         36 return Dancer2::Plugin::Locale::Obj->get_handle( grep( { defined } (@_) ), 'en' ); # multiton already via Locale::Maketext::Utils
  8         124  
28             }
29              
30 11         97 my $app = $dsl->app;
31              
32             # TODO 2: request locale via browser/HTP req after session and before default?
33 11         60 return Dancer2::Plugin::Locale::Obj->get_handle( grep( { defined } ( eval { $app->session->read('locale') }, $dsl->config->{default_locale} ) ), 'en' ); # multiton already via Locale::Maketext::Utils
  22         15972  
  11         233  
34             }
35              
36             sub BUILD {
37 1     1 0 2640 my $dsl = shift;
38              
39 1         5 my @available_locales = ('en');
40              
41             # read locale/ dir for available locales (via config also? likley YAGNI/overly comlicated-why?)
42 1         35 my $locale_dir = File::Spec->catdir( $dsl->app->config->{'appdir'}, 'locale' ); # configurable? nah, why?
43 1 50       101 if ( -d $locale_dir ) {
44 0 0       0 if ( opendir my $dh, $locale_dir ) {
45 0         0 while ( my $file = readdir($dh) ) {
46 0 0       0 next if $file !~ m/\.json$/;
47 0 0       0 next if $file eq 'en.json';
48 0         0 $file =~ s/\.json//;
49 0 0       0 if ( Locales::normalize_tag($file) ne $file ) {
50 0         0 warn "Skipping un-normalized locale named lexicon ($file.json) …\n"; # just no apparent need to complicate things by trying to deal with this
51 0         0 next;
52             }
53              
54 0 0       0 if ( !-f "$locale_dir/$file.json" ) {
55 0         0 warn "Skipping non-file lexicon ($file.json) …\n";
56 0         0 next;
57             }
58              
59 0         0 push @available_locales, $file;
60             }
61 0         0 closedir($dh);
62             }
63             else {
64 0         0 die "Could not read locale directory ($locale_dir): $!\n";
65             }
66             }
67 1     1   9 no strict 'refs'; ## no critic
  1         2  
  1         31  
68 1     1   5 no warnings 'redefine'; ## no critic
  1         2  
  1         138  
69             *Locale::Maketext::Utils::list_available_locales = sub {
70 0     0   0 return ( sort @available_locales );
71 1         41 };
72              
73             # create classes that Locale::Maketext uses
74 1         6 for my $tag (@available_locales) {
75 1         20 my $file = File::Spec->catfile( $locale_dir, "$tag.json" );
76              
77             # TODO 1: for en (and its alias) empty value means key *is* value …
78              
79             # TODO 1: support tieing to CDB_File hash (e.g. if -f locale_cdb/$tag.cdb) so as not to load all the data into memory (see use_external_lex_cache)?
80              
81             # TODO 2: POD app w/ charset !utf8 == ick
82 1     1   12 eval "package Dancer2::Plugin::Locale::Obj::$tag;use base 'Dancer2::Plugin::Locale::Obj';our \$Encoding='utf8';our \%Lexicon;package Dancer2::Plugin::Locale;"; ## no critic
  1         4  
  1         505  
  1         105  
83              
84 1     1   10 no strict 'refs'; ## no critic
  1         3  
  1         264  
85             #
86 1 50 33     22 my $hr = $tag eq 'en' && !-e $file ? {} : ( _from_json_file($file) || {} );
      0        
87 1         3 %{"Dancer2::Plugin::Locale::Obj::$tag\::Lexicon"} = %{$hr};
  1         7  
  1         3  
88              
89             # TODO 1: instead: tie %{"Dancer2::Plugin::Locale::$tag\::Lexicon"}, 'Tie::Hash::ReadonlyStack', _from_json_file($file);
90             }
91              
92             # TODO 2: Is there a better way to add template keyword?
93             $dsl->app->add_hook(
94             Dancer2::Core::Hook->new(
95             name => 'before_template_render',
96             code => sub {
97 6     6   38463 $_[0]->{locale} = sub { $dsl->locale(@_) };
  6         51767  
98             },
99             )
100 1         55 );
101             }
102              
103             sub _from_json_file {
104 0     0     my ($file) = @_;
105 0 0         open( my $fh, '<', $file ) or die "Could not read “$file”: $!";
106 1     1   643 use Dancer2::Serializer::JSON;
  1         39951  
  1         108  
107 0           my $ref = {};
108 0           eval {
109             $ref = Dancer2::Serializer::JSON::from_json(
110 0           do { local $/; <$fh> }
  0            
  0            
111             );
112             };
113 0 0         if ($@) {
114              
115 0           warn "Ignoring lexicon, $file, since it containes invalid JSON:\n\t$@";
116             }
117 0           return $ref;
118             }
119              
120             # TODO 2: localization tips
121             # TODO 2: extractor/checker tool
122              
123             1;
124              
125             __END__
126              
127             =encoding utf8
128              
129             =head1 NAME
130              
131             Dancer2::Plugin::Locale - Localize your Dancer2 application
132              
133             =head1 VERSION
134              
135             This document describes Dancer2::Plugin::Locale version 0.07
136              
137             =head1 SYNOPSIS
138              
139             In your app:
140              
141             use Dancer2;
142             use Dancer2::Plugin::Locale;
143              
144             …
145             locale->maketext('You are [numf,_1] of [numf,_2].', 42, 99);
146             …
147              
148             and from template
149              
150             <div id="req_msg">[% locale.maketext('You have [quant,_1,request,requests].', req_count) %]</div>
151              
152             =head1 DESCRIPTION
153              
154             Adds a C<locale> keyword for your code and templates.
155              
156             =head1 INTERFACE
157              
158             =head2 locale
159              
160             A lazy façade to get a locale handle suitable to the request. The locale object is a CLDR aware maketext format object.
161              
162             It will be based on the session’s locale value if possible, then a configured default if possible, then 'en'.
163              
164             =head2 The object, in more detail
165              
166             The object is L<Locale::Maketext::Utils> based.
167              
168             L<Locale::Maketext::Utils> extends L<Locale::Maketext> a number of ways including:
169              
170             =over 4
171              
172             =item * It shifts toward CLDR based functionality which means you no longer have to create locale specific variants of code in each locale’s class.
173              
174             =item * Because of that and other utils it has, creating and dealing with the locale subclasses classes is much easier.
175              
176             =item * The object is a multiton (AKA an argument based singleton): L<Locale::Maketext::Utils/"Argument based singleton">
177              
178             =item * Adds a number of helpful methods: L<Locale::Maketext::Utils/METHODS>
179              
180             =item * More sane fallback and lookup failure hooks: L<Locale::Maketext::Utils/"Automatically _AUTO'd Failure Handling with hooks">
181              
182             =item * Adds a very handy set of bracket notation methods (CLDR when possible) L</"Bracket Notation">
183              
184             =back
185              
186             =head3 Available Locales
187              
188             The locales available are determined by the lexicon files found in the appdir’s C<locale/> directory.
189              
190             The name of each file must be a normalized version (See Locales::normalize_tag() in L<Locales>) of an L<acceptable ISO tag|Locales/"Supported_Locale_Criteria">. and end in with the extension C<.json>.
191              
192             Tip: To make them available to your UI you could simply symlink C<…/locale/> to C<…/public/locale>.
193              
194             =head3 Lexicon
195              
196             A lexicon is a simple key/value hash where the key is the phrase and the value is the translation.
197              
198             For example,in pseudo code:
199              
200             # source phrase => target phrase
201             'Hello World' => 'Bonjour Monde'
202              
203             Each locale will have a lexicon hash in a file as desrcibed in L</"Available Locales">.
204              
205             The hash must be written in JSON format and be utf8 encoded.
206              
207             Don’t be afraid of non-ASCII characters, just put them in the file as the character and it will work fine (if it doesn’t then it can help you track down bugs faster, win win!).
208              
209             "I ♥︎ Dancer2!" : "私は♥︎ダンサー2"
210              
211             =head3 Bracket Notation
212              
213             Bracket notation is described a bit more at L<Locale::Maketext/BRACKET NOTATION> but is essentially a format to allow you to notate–within left and right square brackets, hence the name–dynamic portions of a phrase.
214              
215             For example, include a non-translatable ever-changing name:
216              
217             locale->maketext('Your email address, [_1], has been unsubscribed.', $email)
218              
219             or a number formatted according to the object’s locale’s CLDR data:
220              
221             locale->maketext('You are user [numf,_1] of [numf,_2].', $place, $count)
222              
223             The bracket notation improvements over the core L<Locale::Maketext> can be categoraized as follows:
224              
225             =over 4
226              
227             =item * L<improved core Locale::Maketext bracket notation methods|http://search.cpan.org/perldoc?Locale::Maketext::Utils#Improved_Bracket_Notation>
228              
229             =item * L<additional bracket notation methods|http://search.cpan.org/perldoc?Locale::Maketext::Utils#Additional_bracket_notation_methods>
230              
231             =item * L<output() bracket notation methods|http://search.cpan.org/perldoc?Locale::Maketext::Utils#output()>
232              
233             =back
234              
235             =head2 Misc Info
236              
237             =head3 Only load the lexicon data you need!
238              
239             … TODO, sorry I needed to get this on CPAN for a consumer but will finish it ASAP …
240              
241             =head4 per app/route loading/unloading of specific lexicon
242              
243             … TODO, sorry I needed to get this on CPAN for a consumer but will finish it ASAP …
244              
245             =head4 only load the keys you use
246              
247             =head3 Localization Principles
248              
249             … TODO, sorry I needed to get this on CPAN for a consumer but will finish it ASAP …
250              
251             =head3 Extracting and Vetting phrases from your app
252              
253             … TODO, sorry I needed to get this on CPAN for a consumer but will finish it ASAP …
254              
255             =head2 TODOs
256              
257             TODO items in the POD obviously, will list more if there are any left after the next version.
258              
259             =head1 DIAGNOSTICS
260              
261             =head2 Errors
262              
263             If the C<locale/> directory exists but can not be opened:
264              
265             C<<Could not read locale directory (%s): $!>>
266              
267             =head2 Warnings
268              
269             If you have a mis-named file in your C<locale/> directory:
270              
271             C<<Skipping un-normalized locale named lexicon (%s.json) …>>
272              
273             If you have a properly named lexicon that is not a file in your C<locale/> directory:
274              
275             C<<Skipping non-file lexicon (%s.json) …>>
276              
277             If you have a lexicon that can’t be loaded (e.g. broken JSON):
278              
279             C<<Ignoring lexicon, %s, since it containes invalid JSON:\n\t$@>>
280              
281             =head1 CONFIGURATION AND ENVIRONMENT
282              
283             The default locale is “en”, you can change it via Dancer2 configuration like so:
284              
285             plugins:
286             Locales:
287             default_locale: ja
288              
289             =head1 DEPENDENCIES
290              
291             L<Dancer2::Plugin>
292              
293             L<Locale::Maketext::Utils>
294              
295             L<Locales>
296              
297             L<File::Spec>
298              
299             =head1 INCOMPATIBILITIES
300              
301             None reported.
302              
303             =head1 BUGS AND FEATURES
304              
305             Please report any bugs or feature requests (and a pull request for bonus points)
306             through the issue tracker at L<https://github.com/drmuey/p5-Dancer2-Plugin-Locale/issues>.
307              
308             =head1 AUTHOR
309              
310             Daniel Muey C<< <http://drmuey.com/cpan_contact.pl> >>
311              
312             =head1 LICENCE AND COPYRIGHT
313              
314             Copyright (c) 2015, Daniel Muey C<< <http://drmuey.com/cpan_contact.pl> >>. All rights reserved.
315              
316             This module is free software; you can redistribute it and/or
317             modify it under the same terms as Perl itself. See L<perlartistic>.
318              
319             =head1 DISCLAIMER OF WARRANTY
320              
321             BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
322             FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
323             OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
324             PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
325             EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
326             WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
327             ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
328             YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
329             NECESSARY SERVICING, REPAIR, OR CORRECTION.
330              
331             IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
332             WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
333             REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
334             LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
335             OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
336             THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
337             RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
338             FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
339             SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
340             SUCH DAMAGES.