in reply to Extensions via Moose
can Moose add a role ("traits") to an instance after it has been created
Yes, this can be done in a couple different ways. First, there is MooseX::Traits which is probably the best way to do this as it is battle tested code that just does the right thing for you, a simple skim of the POD should give you an idea of its capabilities.
Next, you can use Moose::Util which has apply_all_roles which will not only apply roles to the $applicant, but will handle any type of role parameterization correctly as well. Basically it takes, as a second argument, the same type of list that the with keyword takes.
If you are going to do this often, you might also want to look at Moose::Util::with_traits, which will create the anon-class for you from the list of roles and return the class name so that you can then use it to create new instances, like so:
my $class = Moose::Util::with_traits( $a_class, @bunch_of_roles ); my $instance = $class->new;
Lastly, you can do it the "hard" way, which is to say, do it by hand yourself using the MOP. The simplest way is to use the Role meta-object like so:
This will do the right thing for instances, classes and roles. And if you have multiple roles you want to apply you can do this:My::Role->meta->apply( $some_instance );
But really, you want MooseX::Traits, it is simple and pretty much does exactly what you are looking for.Moose::Meta::Role->combine( @role_meta_objects )->apply( $some_instanc +e );
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Extensions via Moose
by John M. Dlugosz (Monsignor) on Apr 29, 2011 at 00:16 UTC | |
by stvn (Monsignor) on Apr 29, 2011 at 13:56 UTC | |
by John M. Dlugosz (Monsignor) on Apr 30, 2011 at 08:23 UTC | |
by stvn (Monsignor) on May 01, 2011 at 01:48 UTC | |
by John M. Dlugosz (Monsignor) on Apr 30, 2011 at 09:06 UTC | |
by stvn (Monsignor) on May 01, 2011 at 01:56 UTC |