After creating a metaclass using Moose::Meta::Class->create
, how do I instantiate a real Moose class with that class as a metaclass?
(I need to create the metaclass also because I also want to apply some roles to it.)

- 16,256
- 15
- 86
- 137

- 5,037
- 6
- 28
- 26
2 Answers
Not sure this answers this or your other SO question How do I build a Moose class at runtime, add a method to it, apply a role to it and instantiate it once? How would you approach this?
at Building a Moose class at runtime and tuning it but have a look at:
It may do what you want. Or you may find it useful to peer into our it works.
The documentation does provide links to blog posts I made while coming to grips with building this module so you may find those helpful also.
Here is an brief code example of MooseX::SingletonMethod:
{
package Foo;
use MooseX::SingletonMethod;
sub bar { say 'bar' }
}
my $baz = Foo->new;
my $bar = Foo->new;
$baz->add_singleton_method( baz => sub { say 'baz' } );
$baz->bar; # => bar
$bar->bar; # => bar
$baz->baz; # => baz
$bar->baz; # Throws can't find baz error
/I3az/
The metaclass is the class, of course. If you want an instance of that class, just do:
my $instance = $meta->name->new
You might also need to make sure that $meta doesn't get collected too soon. Generally, you do this:
$meta->add_method( meta => sub { $meta } );
That will keep the metaclass around, but you're going to leak the class if you aren't careful. If you only do this once, it won't matter; if you do it thousands of times, you could get yourself into trouble.
Much better to use something higher-level like Moose::Meta::Class::create_anon_class
or MooseX::Traits
.

- 42,082
- 9
- 61
- 86
-
ah yes thank you jrockway :) I didn't even know what $meta->name was supposed to do, that is *HIGHLY* , I repeat, *HIGHLY* unintuitive for a method name... oh well ... the world of software – xxxxxxx Mar 10 '10 at 14:49
-
3@xxxxxxxx - uh, `name` just returns the name of the package/class. How is that unintuitive? See http://search.cpan.org/dist/Class-MOP/lib/Class/MOP/Package.pm – daotoad Mar 10 '10 at 15:39
-
You could also use `new_object` on the metaclass. http://search.cpan.org/~flora/Class-MOP-1.12/lib/Class/MOP/Class.pm#Object_instance_construction_and_cloning – ocharles Jan 18 '11 at 19:06