in reply to Re^2: on the fly methods
in thread on the fly methods
Actually Class::MOP does not provide for a (direct) way to add methods to an instance, it mostly deals with just classes. And with Moose, there is no way to add a single method on a per-instance basis really either, you do it with runtime Roles instead, like this:
Also Class::Trait does this same type of thing using Traits instead of Roles.{ package My::Class; use Moose; sub hello { "Hello" } package My::Role; use Moose::Role; sub foo { "Foo" } } my $obj_1 = My::Class->new; my $obj_2 = My::Class->new; My::Role->meta->apply($obj_1); print $obj_1->foo; # print "Foo" print $obj_2->foo; # dies with a method not found error
Ruby accomplishes this type of thing with "Eigenclasses" which were in the Perl 6 metamodel at one time, but were not backported to Moose (because they tended to make simple metaclass things overly complex). The Ruby idiom of:
roughly translates into this:class << obj def new_method "fweeee" end end
where add_singleton_method is just a method in Object. Something like this could be added to Moose without too much trouble at all really (no AUTOLOAD tricks needed either).obj.add_singleton_method(lambda { "fweee" })
|
|---|