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