我正在尝试扩展Set :: Object以便在插入对象时允许类型约束检查。到目前为止,我的班级看起来像这样:
package My::Set::Object;
use strict;
use warnings;
use Moose;
use MooseX::NonMoose;
extends 'Set::Object';
has type => (is => 'ro', isa => 'Str', required => 1);
before [ qw(insert invert intersection union) ] => sub {
my ($self,$list) = @_;
for (@$list) {
confess "Only ",$self->type," objects are allowed " unless $_->does($self->type);
}
};
no Moose;
__PACKAGE__->meta->make_immutable;
不幸的是,当我执行以下示例对象构造时,似乎构造参数也传递给Set :: Object
my $set = My::Set::Object->new(type => 'Foo::Bar');
打印出set的内容后,我发现"键入"和" Foo :: Bar"是该集的成员。
我该如何解决这个问题?或者是否有更简单的方法可以做到这一点?
答案 0 :(得分:6)
这里,作为一个实际答案。我通常按照这些方式进行编码,并且应该做你需要的。警告:我没有测试过这段代码,它甚至可能无法编译,但它应该让你走上正轨。与此子类化的唯一真正区别是 - >检查'Set :: Object'时,My :: Set :: Object对象上的ISA不会成立。
package My::Set::Object;
use strict;
use warnings;
use Moose;
use Set::Object;
my @methods = qw/insert includes has contains invert intersection union/; # etc etc.
has type => (is => 'ro', isa => 'Str', required => 1);
has _so => (is => 'ro', isa => 'Set::Object', handles => \@methods, lazy_build => 1);
before [ qw(insert invert intersection union) ] => sub {
my ($self,$list) = @_;
for (@$list) {
confess "Only ",$self->type," objects are allowed " unless $_->does($self->type);
}
};
sub _build__so {
return Set::Object->new()
}
no Moose;
__PACKAGE__->meta->make_immutable;