Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Moose Handles and Roles

by elTriberium (Friar)
on Jun 16, 2011 at 23:02 UTC ( #910048=perlquestion: print w/replies, xml ) Need Help??

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; # 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', },
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!

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://910048]
Approved by ikegami
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2023-05-28 02:01 GMT
Find Nodes?
    Voting Booth?

    No recent polls found