comparison Lib/IMPL/Resources.pm @ 318:1838bdb4d238

corrected support of resources localization
author cin
date Tue, 14 May 2013 03:38:47 +0400
parents 16ada169ca75
children d485467eca92
comparison
equal deleted inserted replaced
317:96a522aeb359 318:1838bdb4d238
1 package IMPL::Resources; 1 package IMPL::Resources;
2 use strict; 2 use strict;
3 use warnings;
4 3
5 our $Encoding ||= 'utf-8'; 4 our $CurrentLocale ||= 'default';
6 our %Files;
7 5
8 my %Data; 6 sub CurrentLocale {
9 7 $CurrentLocale;
10
11 foreach my $group (keys %Files) {
12 $Data{$group} = ParseResource($Files{$group});
13 }
14
15 sub findFile {
16 my ($fname) = @_;
17
18 foreach my $dir (',',@INC) {
19 my $fullfname = "$dir/$fname";
20 return $fullfname if -f $fullfname;
21 }
22
23 return $fname;
24 }
25
26 sub ParseResource {
27 my ($fname) = @_;
28
29 open my $hRes, "<:encoding($Encoding)", findFile($fname) or die "Failed to open file $fname: $!";
30
31 my %Map;
32 my $line = 1;
33 while (<$hRes>) {
34 chomp;
35 $line ++ and next if /^\s*$/;
36
37 if (/^(\w+)\s*=\s*(.*)$/) {
38 $Map{$1} = $2;
39 } else {
40 die "Invalid resource format in $fname at $line";
41 }
42 $line ++;
43 }
44
45 return \%Map;
46 } 8 }
47 9
48 sub import { 10 sub SetLocale {
49 my ($class,@groups) = @_; 11 my ($self,$locale) = @_;
50 my $caller = caller;
51 my %merged = map %{$Data{$_} || {} }, @groups;
52 12
53 no strict 'refs'; 13 $CurrentLocale = $locale;
54 foreach my $item ( keys %merged ) { 14 }
55 *{"${caller}::ids_$item"} = sub { sprintf($merged{$item},@_) } 15
56 } 16 sub InvokeInLocale {
17 my ($this,$locale,$code) = @_;
18
19 local $CurrentLocale = $locale;
20 eval {
21 &$code()
22 if $code;
23 };
24 die $@
25 if $@;
57 } 26 }
58 27
59 1; 28 1;