strict/warnings, and explanatory comments
[gitmo/MooseX-UndefTolerant.git] / lib / MooseX / UndefTolerant / Constructor.pm
CommitLineData
2d1c57bd 1package MooseX::UndefTolerant::Constructor;
02e25b00 2
3# applied to constructor method metaclass, for Moose < 1.9900
4
2d1c57bd 5use Moose::Role;
6
02e25b00 7use strict;
8use warnings;
9
e5d1b642 10around _generate_slot_initializer => sub {
11 my $orig = shift;
12 my $self = shift;
2dca5fcf 13
e5d1b642 14 # note the key in the params may not match the attr name.
15 my $key_name = $self->_attributes->[$_[0]]->init_arg;
2dca5fcf 16
e5d1b642 17 # insert a line of code at the start of the initializer,
18 # clearing the param if it's undefined.
2dca5fcf 19
e5d1b642 20 if (defined $key_name)
21 {
22 # leave the value unscathed if the attribute's type constraint can
23 # handle undef (or doesn't have one, which implicitly means it can)
24 my $type_constraint = $self->_attributes->[$_[0]]->type_constraint;
25 if ($type_constraint and not $type_constraint->check(undef))
2dca5fcf 26 {
e5d1b642 27 my $tolerant_code =
28 qq# delete \$params->{'$key_name'} unless # .
29 qq# exists \$params->{'$key_name'} && defined \$params->{'$key_name'};\n#;
2dca5fcf 30
e5d1b642 31 return $tolerant_code . $self->$orig(@_);
2dca5fcf 32 }
e5d1b642 33 }
2dca5fcf 34
e5d1b642 35 return $self->$orig(@_);
36};
2d1c57bd 37
38no Moose::Role;
2d1c57bd 391;