如何修改Moose属性句柄?

时间:2010-10-23 19:49:04

标签: perl moose

关注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修饰符,但无法想出如何修改句柄(而不仅仅是对象方法)。

或者,是否有另一种方法来实现这种呱呱叫 - 如果尝试读取 - 不存在 - 键?

1 个答案:

答案 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);
};