How do I compose an existing Moose role into a class at runtime?
Posted
by Oesor
on Stack Overflow
See other posts from Stack Overflow
or by Oesor
Published on 2010-06-08T19:44:58Z
Indexed on
2010/06/08
20:22 UTC
Read the original article
Hit count: 440
Say I define an abstract My::Object and concrete role implementations My::Object::TypeA and My::Object::TypeB. For maintainability reasons, I'd like to not have a hardcoded table that looks at the object type and applies roles. As a DWIMmy example, I'm looking for something along these lines in My::Object:
has => 'id' (isa => 'Str', required => 1);
sub BUILD {
my $self = shift;
my $type = $self->lookup_type(); ## Returns 'TypeB'
{"My::Object::$type"}->meta->apply($self);
}
Letting me get a My::Object with My::Object::TypeB role applied by doing the following:
my $obj = My::Object(id = 'foo')
Is this going to do what I want or am I on the entirely wrong track?
Edit: I simplified this too much; I don't want to have to know the type when I instantiate the object, I want the object to determine its type and apply the correct role's methods appropriately. I've edited my question to make this clearer.
© Stack Overflow or respective owner