如何修改 Moose 属性句柄?
按照 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 { {} }
现在,假设如果尝试读取(但不写入)不存在的自定义字段,我会发出嘎嘎声。 phaylon 建议我用 around 修饰符包裹 custom_field
。我按照 Moose 文档中的各种示例尝试了 around
修饰符,但无法弄清楚如何修改句柄(而不仅仅是对象方法)。
或者,是否有另一种方法来实现此“如果尝试读取不存在的密钥则发出嘎嘎声”?
Following phaylon's answer to "How can I flexibly add data to Moose objects?", suppose I have the following Moose attribute:
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 { {} }
Now, suppose I'd like to croak if trying to read (but not write) to a non-existing custom field. I was suggested by phaylon to wrap custom_field
with an around modifier. I have experimented with around
modifiers following the various examples in Moose docs, but couldn't figure how to modify a handle (rather than just an object method).
Alternatively, is there another way to implement this croak-if-try-to-read-nonexisting-key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它们仍然只是 Moose 生成的方法。你可以这样做:(
croak
目前在方法修饰符中不是很有用。它只会指向内部 Moose 代码。)事实上,你不需要使用
around为此。使用
before
更简单:They're still just methods generated by Moose. You can just do:
(
croak
is not very useful in method modifiers at the moment. It will just point you at internal Moose code.)In fact, you don't need to use
around
for this. Usingbefore
is simpler: