http://qs1969.pair.com?node_id=910048

elTriberium has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

I just ran into a problem that to me looks like Moose Handles and Roles don't work together well. Please take a look at the following role, class and test program:

# TestRole role: package TestRole; use Moose::Role; requires 'test_method'; 1; # Consumer class: package Consumer; use Moose; with 'TestRole'; has 'test_attribute' => ( traits => ['Array'], is => 'rw', isa => 'ArrayRef[Str]', default => sub { [] }, handles => { test_method => 'elements', add_something => 'push', }, ); 1; # tester.pl: use Data::Dumper; use Consumer; my $c = Consumer->new(); $c->add_something("123"); my @arr = $c->test_method(); print Dumper(\@arr) . "\n";

Now when I try to run this it tells me:

'TestRole' requires the method 'test_method' to be implemented by 'Con +sumer'

From reading the following part of the Moose manual about roles I understand that this is the desired behaviour. "It should be noted that this does not include any method modifiers or generated attribute methods (which is consistent with role composition)." But I don't understand the motivation for it. Why shouldn't I be able to define the handles as required by the role? I want to use the Role as a handle itself in another class to delegate all those methods, including the attribute handles. Why isn't that allowed? Does that mean my only option is to manually write subs for the handles (e.g. convert

handles => { test_method => 'elements', add_something => 'push', },
into
sub add_something { my ($self, %args) = @_; # manually push here... } sub test_method { # add the 'elements' code here. }
Thanks for your help!

Replies are listed 'Best First'.
Re: Moose Handles and Roles
by ikegami (Patriarch) on Jun 17, 2011 at 00:15 UTC
    has hasn't yet been called to create test_method when with is called. Move the with to after the has, or put the has in a BEGIN block..
      Wow, it's really that simple? Thanks!