How can I modify a Moose attribute handle?

微笑、不失礼 提交于 2019-12-08 07:54:49

问题


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?


回答1:


They're still just methods generated by Moose. You can just do:

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 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. Using before is simpler:

before 'custom_field' => sub {
    my $self  = shift;
    my $field = shift;

    confess "No $field" unless @_ or $self->has_custom_field($field);
};


来源:https://stackoverflow.com/questions/4005751/how-can-i-modify-a-moose-attribute-handle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!