Friday, 6 November 2009

Extending a Role attribute

Not so much a blog post, more a blog question.

When you are 'extend'ing a Moose base class, Attributes can be extended

package Super::Hero;
use Moose;

has q{super_abilitity} => (isa => q{Str}, is => q{rw});

...

package My::Hero;
use Moose;
extends qw{Super::Hero};

has q{+super_abilitity} => (required => 1);

...


However, in this case, I would like Super::Hero to be a Role to be consumed by some class.

package Super::Hero;
use Moose::Role;

has q{super_abilitity} => (isa => q{Str}, is => q{rw});

...

However, the following doesn't work:

package My::Hero;
use Moose;

with qw{Super::Hero};

has q{+super_abilitity} => (required => 1);

...

The required 'extension' is just ignored. I have to actually declare the whole attribute again.

package My::Hero;
use Moose;

with qw{Super::Hero};

has q{super_abilitity} => (isa => q{Str}, is => q{ro}, required => 1);

...

I can't find anything in CPAN Documentation to confirm or deny that this the deliberate design. Does anyone have any suggestions as to any solutions to this?

Any help appreciated.

3 comments:

j1n3l0 said...

That's because you "consume" roles not "extend" them. Thus all your "My::Hero" class needs to do to get the "Super::Hero" "super_ability" is to include the following line of code:

with 'Super::Hero';

Andy Brown - SetitesUK said...

Thanks for your reply.

I was really wondering if there is a way to alter something you are consuming, rather than needing to overwrite it. It looks like that seems to be a rule of Roles, you don't get to tamper with them, just not use (exclude and/or overwrite) their attributes/methods.

But again, thankyou for taking the time to reply. BTW, where are you a Computer Biologist in Cambridge, UK?

Andy Brown - SetitesUK said...

Forget where are you working question, I found out that we both work at the Sanger through my boss. I could be interested in discussing you Parallelize.pm module at some time.