1e5e91c316daa40f18a0bbe10cf9d48fc45e3c7c
[gitmo/MooseX-UndefTolerant.git] / lib / MooseX / UndefTolerant / Class.pm
1 package MooseX::UndefTolerant::Class;
2
3 # applied to metaclass, for Moose >= 1.9900
4
5 use strict;
6 use warnings;
7
8 use Moose::Role;
9
10 # TODO: this code should be in the attribute trait, in the inlined version of
11 # initialize_instance_slot, but this does not yet exist!
12
13 around _inline_init_attr_from_constructor => sub {
14     my $orig = shift;
15     my $self = shift;
16     my ($attr, $idx) = @_;
17
18     my @source = $self->$orig(@_);
19
20     my $init_arg = $attr->init_arg;
21     my $type_constraint = $attr->type_constraint;
22     my $tc_says_clean = ($type_constraint && !$type_constraint->check(undef) ? 1 : 0);
23
24     return ($tc_says_clean ? (
25         "if ( exists \$params->{'$init_arg'} && defined \$params->{'$init_arg'} ) {",
26         ) : (),
27         @source,
28         $tc_says_clean ? (
29         '} else {',
30             "delete \$params->{'$init_arg'};",
31         '}',
32         ) : (),
33     );
34 };
35
36 no Moose::Role;
37 1;