do not use Undef-Tolerant behaviour on attributes that are capable of handling undef
[gitmo/MooseX-UndefTolerant.git] / lib / MooseX / UndefTolerant / Constructor.pm
CommitLineData
2d1c57bd 1package MooseX::UndefTolerant::Constructor;
2use Moose::Role;
3
d6ce838b 4if ( $Moose::VERSION < 1.9900 ) {
5 around('_generate_slot_initializer', sub {
6 my $orig = shift;
7 my $self = shift;
8e67fa0c 8
d6ce838b 9 # note the key in the params may not match the attr name.
10 my $key_name = $self->_attributes->[$_[0]]->init_arg;
2d1c57bd 11
d6ce838b 12 # insert a line of code at the start of the initializer,
13 # clearing the param if it's undefined.
2d1c57bd 14
3991a5d2 15 if (defined $key_name)
16 {
17 # leave the value unscathed if the attribute's type constraint can
18 # handle undef (or doesn't have one, which implicitly means it can)
19 my $type_constraint = $self->_attributes->[$_[0]]->type_constraint;
20 if ($type_constraint and not $type_constraint->check(undef))
21 {
22 my $tolerant_code =
23 qq# delete \$params->{'$key_name'} unless # .
d6ce838b 24 qq# exists \$params->{'$key_name'} && defined \$params->{'$key_name'};\n#;
d10a4d7f 25
d6ce838b 26 return $tolerant_code . $self->$orig(@_);
3991a5d2 27 }
d6ce838b 28 }
3991a5d2 29
30 return $self->$orig(@_);
31});
2d1c57bd 32
33no Moose::Role;
34
351;