如何修改 Moose 属性句柄?

发布于 2024-09-28 15:05:42 字数 904 浏览 3 评论 0原文

按照 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幸福%小乖 2024-10-05 15:05:42

它们仍然只是 Moose 生成的方法。你可以这样做:(

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

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);
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文