make unsupported language non-fatal; correct exception raising
[scpubgit/stemmatology.git] / morphology / lib / Text / Tradition / Language.pm
CommitLineData
e92d4229 1package Text::Tradition::Language;
2
3use strict;
4use warnings;
332750fc 5use Module::Load;
e92d4229 6use Moose::Role;
142698b8 7use TryCatch;
e92d4229 8
332750fc 9requires 'throw';
10
e92d4229 11=head1 NAME
12
13Text::Tradition::Language - add-on role to enable language awareness and
8943ff68 14morphology functions to a Text::Tradition object. Please see
15L<Text::Tradition::Morphology> for more information on the morphology
16add-on distribution.
e92d4229 17
18=head1 METHODS
19
20=head2 language
21
22Accessor for the primary language of the tradition. Must correspond to one
23of the Text::Tradition::Language::* modules in this package.
24
142698b8 25=begin testing
26
27use Test::Warn;
28use TryCatch;
29use_ok( 'Text::Tradition' ); # with Language
30
31# Test setting and recovering language
32my $t = Text::Tradition->new( input => 'Self', file => 't/data/legendfrag.xml' );
33warning_like { $t->language( 'Klingon' ); } qr/^Cannot load language/,
34 "Got expected warning for setting of unsupported language";
35$t->language( 'English' );
36is( $t->language, 'English', "Successfully set supported language" );
37
38# Test bad attempt to lemmatize - proper lemmatization is tested separately
39my $bt = Text::Tradition->new( input => 'Self', file => 't/data/besoin.xml' );
40try {
41 $bt->lemmatize;
42 ok( 0, "Failed to throw error on lemmatizing without language" );
43} catch( Text::Tradition::Error $e ) {
44 is( $e->message, "Please set a language to lemmatize a tradition",
45 "Got correct error thrown for lemmatization without set language" );
46} catch {
47 ok( 0, "Unexpected error on bad lemmatization attempt" );
48}
49
50=end testing
51
e92d4229 52=cut
53
54has 'language' => (
55 is => 'rw',
56 isa => 'Str',
57 predicate => 'has_language',
58 );
59
60before 'language' => sub {
61 my $self = shift;
62 if( @_ && $_[0] ne 'Default' ) {
63 # We are trying to set the language; check that the corresponding
64 # module exists.
142698b8 65 try {
66 load( "Text::Tradition::Language::".$_[0] );
67 } catch ( $e ) {
68 warn( "Cannot load language module for @_: $e" );
e92d4229 69 }
70 }
71};
72
73=head2 lemmatize
74
75Calls the appropriate lemmatization function for the language of the
76tradition.
77
78=cut
79
80sub lemmatize {
81 my $self = shift;
82 unless( $self->has_language ) {
142698b8 83 $self->throw( "Please set a language to lemmatize a tradition" );
e92d4229 84 }
85 my $mod = "Text::Tradition::Language::" . $self->language;
142698b8 86 try {
87 load( $mod );
88 } catch ( $e ) {
89 $self->throw( "Cannot load language module for " . $self->language );
90 }
91 $self->throw( "Language module $mod has no lemmatize function" )
92 unless $mod->can( 'lemmatize' );
e92d4229 93 $mod->can( 'lemmatize' )->( $self );
94}
95
961;
97