在我正在编写的 Moose 扩展中,我试图从属性中访问属性值,而不通过访问器,但我似乎无法做到这一点。
我正在尝试编写此代码
{
package Test;
use Moose;
use MooseX::RemoteName; #provides magic
has attr0 => (
isa => 'Bool',
is => 'ro',
default => sub { 1 },
serializer => sub {
my $s = shift;
return $s->get_value( $s ) ? 'Y' : 'N';
},
);
has attr1 => (
isa => 'Str',
is => 'ro',
)
}
这样我就可以(从我的测试中)
my $t0 = Test->new({ attr1 => 'foo' });
isa_ok my $attr0 = $t0->meta->get_attribute('attr0'), 'Class::MOP::Attribute';
is $attr0->serialized, 'Y', 'remote_name serializes';
isa_ok my $attr1 = $t0->meta->get_attribute('attr1'), 'Class::MOP::Attribute';
is $attr1->serialized, 'foo', 'remote_name serializes'; # undef
这就是我在扩展中尝试的
has serializer => (
isa => 'CodeRef',
is => 'ro',
lazy => 1,
default => sub {
return sub {
my $arg = shift;
return $arg->get_value( $arg->associated_class );
}
},
);
sub serialized {
my $self = shift;
my $coderef = $self->serializer;
return &$coderef( $self );
}