关注phaylon's answer to "How can I flexibly add data to Moose objects?",假设我有以下Moose属性:
has custom_fields => (
traits => [qw( Hash )],
isa => 'HashRef',
builder => '_build_custom_fields',
handles => {
custom_field => 'accessor',
has_custom_field => 'exists',
custom_fields => 'keys',
has_custom_fields => 'count',
delete_custom_field => 'delete',
},
);
sub _build_custom_fields { {} }
现在,假设我想尝试读取(但不是写入)不存在的自定义字段时会发出嘎嘎声。 phaylon建议我使用around修饰符包装custom_field
。我已经按照Moose文档中的各种示例尝试了around
修饰符,但无法想出如何修改句柄(而不仅仅是对象方法)。
或者,是否有另一种方法来实现这种呱呱叫 - 如果尝试读取 - 不存在 - 键?
答案 0 :(得分:6)
它们仍然只是穆斯生成的方法。你可以这样做:
around 'custom_field' => sub {
my $orig = shift;
my $self = shift;
my $field = shift;
confess "No $field" unless @_ or $self->has_custom_field($field);
$self->$orig($field, @_);
};
(croak
目前在方法修饰语中不是很有用。它只会指向内部的Moose代码。)
实际上,您不需要使用around
。使用before
更简单:
before 'custom_field' => sub {
my $self = shift;
my $field = shift;
confess "No $field" unless @_ or $self->has_custom_field($field);
};