strict/warnings, and explanatory comments
[gitmo/MooseX-UndefTolerant.git] / lib / MooseX / UndefTolerant / Constructor.pm
1 package MooseX::UndefTolerant::Constructor;
2
3 # applied to constructor method metaclass, for Moose < 1.9900
4
5 use Moose::Role;
6
7 use strict;
8 use warnings;
9
10 around _generate_slot_initializer => sub {
11     my $orig = shift;
12     my $self = shift;
13
14     # note the key in the params may not match the attr name.
15     my $key_name = $self->_attributes->[$_[0]]->init_arg;
16
17     # insert a line of code at the start of the initializer,
18     # clearing the param if it's undefined.
19
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))
26         {
27             my $tolerant_code =
28                 qq# delete \$params->{'$key_name'} unless # .
29                 qq# exists \$params->{'$key_name'} && defined \$params->{'$key_name'};\n#;
30
31             return $tolerant_code . $self->$orig(@_);
32         }
33     }
34
35     return $self->$orig(@_);
36 };
37
38 no Moose::Role;
39 1;