按照phaylon的回答"如何灵活地向Moose对象添加数据?" ,假设我有以下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 { {} }
Run Code Online (Sandbox Code Playgroud)
现在,假设我想尝试读取(但不是写入)不存在的自定义字段时会呱呱叫.我被phaylon建议custom_field
用一个环绕修饰语包裹.我已经around
按照Moose文档中的各种示例尝试了修饰符,但无法确定如何修改句柄(而不仅仅是对象方法).
或者,是否有另一种方法来实现这个croak-if-try-to-read-unfxisting-key?
它们仍然只是穆斯生成的方法.你可以这样做:
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, @_);
};
Run Code Online (Sandbox Code Playgroud)
(croak
目前在方法修饰语中不是很有用.它只会指向内部的Moose代码.)
实际上,您不需要使用around
此功能.使用before
更简单:
before 'custom_field' => sub {
my $self = shift;
my $field = shift;
confess "No $field" unless @_ or $self->has_custom_field($field);
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
516 次 |
最近记录: |