Dancer2-Plugin-Locale

 view release on metacpan or  search on metacpan

lib/Dancer2/Plugin/Locale.pm  view on Meta::CPAN

package Dancer2::Plugin::Locale;

use strict;
use warnings;

use Dancer2::Plugin;
$Dancer2::Plugin::Locale::VERSION = '0.07';

package Dancer2::Plugin::Locale::Obj;
use Locales 0.33 unicode => 1;
use Locale::Maketext::Utils;
use base 'Locale::Maketext::Utils';
our %Lexicon;

package Dancer2::Plugin::Locale;

use File::Spec;

# use Tie::Hash::ReadonlyStack;

plugin_keywords 'locale';

sub locale {
    my $dsl = shift;

    if (@_) {
        return Dancer2::Plugin::Locale::Obj->get_handle( grep( { defined } (@_) ), 'en' );    # multiton already via Locale::Maketext::Utils
    }

    my $app = $dsl->app;

    # TODO 2: request locale via browser/HTP req after session and before default?
    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
}

sub BUILD {
    my $dsl = shift;

    my @available_locales = ('en');

    # read locale/ dir for available locales (via config also? likley YAGNI/overly comlicated-why?)
    my $locale_dir = File::Spec->catdir( $dsl->app->config->{'appdir'}, 'locale' );                                                                             # configurable? nah, why?
    if ( -d $locale_dir ) {
        if ( opendir my $dh, $locale_dir ) {
            while ( my $file = readdir($dh) ) {
                next if $file !~ m/\.json$/;
                next if $file eq 'en.json';
                $file =~ s/\.json//;
                if ( Locales::normalize_tag($file) ne $file ) {
                    warn "Skipping un-normalized locale named lexicon ($file.json) …\n";                                                                      # just no apparent need to complicate things by trying to deal with this
                    next;
                }

                if ( !-f "$locale_dir/$file.json" ) {
                    warn "Skipping non-file lexicon ($file.json) …\n";
                    next;
                }

                push @available_locales, $file;
            }
            closedir($dh);
        }
        else {
            die "Could not read locale directory ($locale_dir): $!\n";
        }
    }
    no strict 'refs';          ## no critic
    no warnings 'redefine';    ## no critic
    *Locale::Maketext::Utils::list_available_locales = sub {
        return ( sort @available_locales );



( run in 0.681 second using v1.01-cache-2.11-cpan-39bf76dae61 )