Perl: Moose, Using Maybe attribute not die on undef
Problema
Cuando definimos atributos en Moose con constraint en tiempo de ejecución podemos encontrarnos con el siguiente tipo de excepciones:
"Attribute (AttributeName) does not pass the type constraint because: Validation failed for 'Str' with value undef"
Para evitarlo podemos usar "Maybe". A continuación un ejemplo:
Class to Test
package ClassWithMaybe;
use Moose;
has 'atributoSinConstraints' => (
is => 'rw',
isa => 'Maybe[Str]',
default => '',
reader => 'getAtributoSinConstraints',
writer => 'setAtributoSinConstraints'
); # will NOT die on undef
has 'atributoConConstraints' => (
is => 'rw',
isa => 'Str',
reader => 'getAtributoConConstraints',
writer => 'setAtributoConConstraints'
); # will die on undef (esto puede generar la exception mostrada anteriormente)
sub BUILD {
my $self = shift;
$self->setAtributoSinConstraints('') unless defined $self->getAtributoSinConstraints;
}
no Moose; __PACKAGE__->meta->make_immutable;
TEST
package ClassWithMaybeTest;
use Moose;
use Test::More;
use Test::Exception; #cpanm Test::Exception
use ClassWithMaybe;
throws_ok { ClassWithMaybe->new( atributoConConstraints => undef ) }
qr/Validation failed for 'Str' with value undef/; # will die on undef
lives_ok { ClassWithMaybe->new( atributoConConstraints => "with data" ) }
'atributoConConstraints with data ok';
lives_ok { ClassWithMaybe->new( atributoSinConstraints => undef ) }
'atributoSinConstraints supplied as undef'; # will not die on undef
my $classWithMaybe = ClassWithMaybe->new( atributoSinConstraints => undef , atributoConConstraints => "with data");
is $classWithMaybe->getAtributoSinConstraints, '', "atributoSinConstraints is ''";
$classWithMaybe = ClassWithMaybe->new();
$classWithMaybe->setAtributoSinConstraints(undef);# will not die on undef
is $classWithMaybe->getAtributoSinConstraints, undef, "atributoSinConstraints is undef";
done_testing;
Run test
perl ClassWithMaybeTest.t
ok 1 - threw Regexp ((?^:Validation failed for 'Str' with value undef))
ok 2 - atributoConConstraints with data ok
ok 3 - atributoSinConstraints supplied as undef
ok 4 - atributoSinConstraints is ''
ok 5 - atributoSinConstraints is undef
1..5
References: