Search code examples
perlparametersconstructormoose

Disallowing non-attribute parameters in a Moose Class


Is there a way to die if there are extra parameters in a constructor call in Moose that are not attributes? For example, this:

package Shoe;
use Moose;
has 'size'  => (is => 'ro', isa => 'Num');
has 'color' => (is => 'ro', isa => 'Str', default => 'brown');
1;

would die on

my $sneaker = Shoe->new(size => 11, colour => 'white');

because colour is not an attribute of Shoe.

I could swear I've seen a module or something to do this but I can't find it.


Solution

  • For me works MooseX::StrictConstructor:

    package Shoe;
    use Moose;
    use MooseX::StrictConstructor; # <-- that's all what need
    has 'size'  => (is => 'ro', isa => 'Num');
    has 'color' => (is => 'ro', isa => 'Str');
    1;
    
    package main;
    my $sneaker = Shoe->new(size => 11, colour => 'white'); #blows up