Reputation: 5167
I define a method inside a parametrized role that needs to create a new class at run time
using Moose::Meta::Class->create
and apply that exact parametrized role to it. I am also making a new method for that role using
$new_class->meta->add_method( some_name => sub {
my ($self) = @_;
...
})
inside the sub {...} I want to access a method of the consumer class and use it for something, I have tried using $self->get_method
, it didn't work, how do I do this?
Please notice that the $self
inside the sub above is MooseX::Role::Parameterized::Meta::Role::Parameterizable
I also have another question, if I do this:
my $object = Moose::Meta::Class->create(
"some_type",
);
Why isn't $object
of type some_type and it's some ugly MooseX::Role::Parameterized::Meta::Role::Parameterizable
and how do I get to the object of type some_type?
Upvotes: 0
Views: 183
Reputation: 1923
I'm not quite sure what you're trying to do here. Let's assume you have
my $new_class = Moose::Meta::Class->create('FooBar');
then $new_class
is the meta object for FooBar
. So, if you want to add a method to FooBar
you would say
$new_class->add_method(foo => sub { … });
which would basically be the same as
FooBar->meta->add_method(foo => sub { … });
You should also probably use find_meta()
from Moose::Util. This will return the correct meta object (if there is one) even if your class doesn't have a meta
method or it uses it for something else.
As said, I'm not sure this answers your question.
Upvotes: 0
Reputation: 53976
It sounds like your underlying problem is nearly exactly what I described at this question: from within the role definition, you need to get at the class (and its meta-class) of the object or class the role is being applied to. This isn't possible from within normal roles, but it's possible through parameterized roles.
Upvotes: 0
Reputation: 46187
To answer your second question, the reason is because Perl's OO doesn't allow you to add a method to just one instance of a class, so Moose has to fake it by creating a subclass with the extra method and reblessing the unique object into that subclass.
Note that, if you are doing things correctly and doing your introspection with isa
, has
, and/or does
rather than by trying to rely on the name of the object's blessed package, this doesn't matter. The object still isa
some_type, has
all of some_type's attributes, and does
all of some_type's roles even though it's now blessed into a package with an ugly auto-generated name.
Upvotes: 1