also test adding strictness in a subclass -- and fix mutable case (thanks doy!) :)
[gitmo/MooseX-StrictConstructor.git] / lib / MooseX / StrictConstructor / Trait / Class.pm
1 package MooseX::StrictConstructor::Trait::Class;
2
3 use Moose::Role;
4
5 use namespace::autoclean;
6
7 use B ();
8
9 around '_inline_BUILDALL' => sub {
10     my $orig = shift;
11     my $self = shift;
12
13     my @source = $self->$orig();
14
15     my @attrs = (
16         '__INSTANCE__ => 1,',
17         map { B::perlstring($_) . ' => 1,' }
18         grep {defined}
19         map  { $_->init_arg() } $self->get_all_attributes()
20     );
21
22     return (
23         @source,
24         'my %attrs = (' . ( join ' ', @attrs ) . ');',
25         'my @bad = sort grep { !$attrs{$_} } keys %{ $params };',
26         'if (@bad) {',
27             'Moose->throw_error("Found unknown attribute(s) passed to the constructor: @bad");',
28         '}',
29     );
30 };
31
32 # if the Object role is applied first, and then a superclass added, we just
33 # lost our BUILDALL modification.
34 after superclasses => sub
35 {
36     my $self = shift;
37     return if not @_;
38     Moose::Util::MetaRole::apply_base_class_roles(
39         for => $self->name,
40         roles => ['MooseX::StrictConstructor::Role::Object'],
41     )
42 };
43
44 1;
45
46 # ABSTRACT: A role to make immutable constructors strict
47
48 __END__
49
50 =pod
51
52 =head1 DESCRIPTION
53
54 This role simply wraps C<_inline_BUILDALL()> (from
55 C<Moose::Meta::Class>) so that immutable classes have a
56 strict constructor.
57
58 =cut