默认情况下,驼鹿非常宽容。您可以拥有一个名为Cucumber的类,并将未声明的属性(如wheels)传递给构造函数。默认情况下,驼鹿不会对此提示。但是我可能更喜欢Moose而不是die而不是接受未声明的属性。我该如何实现?我似乎记得曾经读过它是有可能的,但是在文档中找不到它说的地方。

package Gurke;
use Moose;
has color => is => 'rw', default => 'green';
no Moose;
__PACKAGE__->meta->make_immutable;

package main; # small test for the above package
use strict;
use warnings;
use Test::More;
use Test::Exception;
my $gu = Gurke->new( color => 'yellow' );
ok $gu->color, 'green';
if ( 1 ) {
    my $g2 = Gurke->new( wheels => 55 );
    ok ! exists $g2->{wheels}, 'Gurke has not accepted wheels :-)';
    # But the caller might not be aware of such obstinate behaviour.
    diag explain $g2;
}
else {
    # This might be preferable:
    dies_ok { Gurke->new( wheels => 55 ) } q(Gurken can't have wheels.);
}
done_testing;

好的,这是说明解决方案的更新测试:
package Gurke;
use Moose;
# By default, the constructor is liberal.
has color => is => 'rw', default => 'green';
no Moose;
__PACKAGE__->meta->make_immutable;

package Tomate;
use Moose;
# Have the Moose constructor die on being passed undeclared attributes:
use MooseX::StrictConstructor;
has color => is => 'rw', default => 'red';
no Moose;
__PACKAGE__->meta->make_immutable;

package main; # small test for the above packages
use strict;
use warnings;
use Test::More;
use Test::Exception;

my $gu = Gurke->new( color => 'yellow' );
ok $gu->color, 'green';
my $g2 = Gurke->new( wheels => 55 );
ok ! exists $g2->{wheels}, 'Gurke has not accepted wheels :-)';
diag 'But the caller might not be aware of such obstinate behaviour.';
diag explain $g2;

diag q(Now let's see the strict constructor in action.);
my $to = Tomate->new( color => 'blue' );
diag explain $to;
dies_ok { Tomate->new( wheels => 55 ) } q(Tomaten can't have wheels.);

done_testing;

最佳答案

只需在您的类(class)中使用MooseX::StrictConstructor即可;这是一个元类特征,已经可以完全满足您的要求。

关于perl - 如何使Moose构造函数在传递未声明的属性时死亡?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5818948/

10-10 13:18