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