provide interface definition role and update translator to check for it
[catagits/catbook-code.git] / lib / LolCatalyst / Lite / Translator.pm
CommitLineData
bc61dfc2 1package LolCatalyst::Lite::Translator;
2
a9517e99 3use Module::Pluggable::Object;
63ed6b50 4
bc61dfc2 5use Moose;
d0dd2387 6use aliased 'LolCatalyst::Lite::Interface::TranslationDriver';
80304984 7use namespace::clean -except => 'meta';
8
9has 'default_target' => (
10 is => 'ro', isa => 'Str', required => 1, default => 'LOLCAT'
11);
12
836279c9 13has '_translators' => (
80304984 14 is => 'ro', isa => 'HashRef', lazy_build => 1
15);
16
836279c9 17sub _build__translators {
80304984 18 my ($self) = @_;
bf960837 19 my $base = __PACKAGE__.'::Driver';
a9517e99 20 my $mp = Module::Pluggable::Object->new(
21 search_path => [ $base ]
22 );
23 my @classes = $mp->plugins;
24 my %translators;
25 foreach my $class (@classes) {
26 Class::MOP::load_class($class);
d0dd2387 27 unless ($class->does(TranslationDriver)) {
28 confess "Class ${class} in ${base}:: namespace does not implement Translation Driver interface";
29 }
a9517e99 30 (my $name = $class) =~ s/^\Q${base}::\E//;
31 $translators{$name} = $class->new;
32 }
33 return \%translators;
80304984 34}
35
36sub translate {
37 my ($self, $text) = @_;
38 $self->translate_to($self->default_target, $text);
39}
40
41sub translate_to {
42 my ($self, $target, $text) = @_;
836279c9 43 $self->_translators->{$target}->translate($text);
80304984 44}
45
46__PACKAGE__->meta->make_immutable;
47
bc61dfc2 481;