|Keep It Simple, Stupid|
Re: Extensions via Mooseby stvn (Monsignor)
|on Apr 28, 2011 at 21:43 UTC||Need Help??|
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:
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:
But really, you want MooseX::Traits, it is simple and pretty much does exactly what you are looking for.