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:

{ 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
Also Class::Trait does this same type of thing using Traits instead of Roles.

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:

class << obj def new_method "fweeee" end end
roughly translates into this:
obj.add_singleton_method(lambda { "fweee" })
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).

-stvn

In reply to Re^3: on the fly methods by stvn
in thread on the fly methods by Ojosh!ro

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.