What's the best way to assign a method body at construction time when using Moose?

邮差的信 提交于 2019-12-05 20:24:34

Pass your 'next' subref into the constructor and save it in an attribute:

has next => (
    isa => 'CodeRef',
    required => 1,
    traits => ['Code'],
    handles => { next => 'execute_method' },
);

With the 'execute_method' handler provided by the native attribute 'Code' trait, you can call the 'next' method as a normal method and it will find the subref body in the attribute.

If you want to pre-define the subref body/ies and decide at construction time which version to use, you could set the value of 'next' in a builder sub according to other conditions of the object:

has next => (
    # ...
    lazy => 1,
    default => sub {
         my $self = shift;
         return sub { ... } if $self->some_condition;
         # etc etc...
    },
);

Another option is to dynamically apply a role:

package Iter;
use Moose;
use Moose::Util qw(apply_all_roles);

has next_role => (is => 'ro');

sub BUILD {
    my $self = shift;
    apply_all_roles($self, $self->next_role);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!