Commit | Line | Data |
1a4f7732 |
1 | package MooseX::StrictConstructor::Trait::Method::Constructor; |
c8a39fc4 |
2 | |
d99e6f32 |
3 | use Moose::Role; |
4 | |
5 | use namespace::autoclean; |
c8a39fc4 |
6 | |
7 | use B (); |
c8a39fc4 |
8 | |
c8a39fc4 |
9 | around '_generate_BUILDALL' => sub { |
10 | my $orig = shift; |
11 | my $self = shift; |
12 | |
13 | my $source = $self->$orig(); |
14 | $source .= ";\n" if $source; |
15 | |
16 | my @attrs = ( |
17 | '__INSTANCE__ => 1,', |
18 | map { B::perlstring($_) . ' => 1,' } |
19 | grep {defined} |
20 | map { $_->init_arg() } @{ $self->_attributes() } |
21 | ); |
22 | |
23 | $source .= <<"EOF"; |
24 | my \%attrs = (@attrs); |
25 | |
26 | my \@bad = sort grep { ! \$attrs{\$_} } keys \%{ \$params }; |
27 | |
28 | if (\@bad) { |
714128ef |
29 | Moose->throw_error("Found unknown attribute(s) passed to the constructor: \@bad"); |
c8a39fc4 |
30 | } |
31 | EOF |
32 | |
33 | return $source; |
bb64c045 |
34 | } if $Moose::VERSION < 1.9900; |
35 | |
36 | around _eval_environment => sub { |
37 | my $orig = shift; |
38 | my $self = shift; |
39 | |
40 | my $env = $self->$orig(); |
41 | |
42 | my %attrs = map { $_ => 1 } |
43 | grep { defined } |
44 | map { $_->init_arg() } |
45 | $self->associated_metaclass()->get_all_attributes(); |
46 | |
47 | $attrs{__INSTANCE__} = 1; |
48 | |
49 | $env->{'%allowed_attrs'} = \%attrs; |
50 | |
51 | return $env; |
52 | } if $Moose::VERSION >= 1.9900; |
c8a39fc4 |
53 | |
c8a39fc4 |
54 | 1; |
55 | |
56 | # ABSTRACT: A role to make immutable constructors strict |
57 | |
58 | __END__ |
59 | |
60 | =pod |
61 | |
c8a39fc4 |
62 | =head1 DESCRIPTION |
63 | |
64 | This role simply wraps C<_generate_BUILDALL()> (from |
65 | C<Moose::Meta::Method::Constructor>) so that immutable classes have a |
66 | strict constructor. |
67 | |
68 | =cut |
69 | |