in reply to Re: on the fly methods
in thread on the fly methods

If you use any of Class::Trait, Class::MOP, or Moose then objects can have their own methods. (I'm guessing that Moose does this because it uses MOP which provides this service).

⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Replies are listed 'Best First'.
Re^3: on the fly methods
by stvn (Monsignor) on Feb 27, 2007 at 21:49 UTC

    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
Re^3: on the fly methods
by friedo (Prior) on Feb 27, 2007 at 16:48 UTC
Re^3: on the fly methods
by jettero (Monsignor) on Feb 27, 2007 at 16:55 UTC
    I had never heard of Moose before this, but I think it's potentially something I could one day use in all my new OO code. Wow, just wow.

    -Paul

      I think Moose is a port of Perl 6's OO system back to Perl 5.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        AIUI that's how it started, but to quote from Moose's docs themselves:

        Is Moose just Perl 6 in Perl 5?

        No. While Moose is very much inspired by Perl 6, it is not itself Perl 6. Instead, it is an OO system for Perl 5. I built Moose because I was tired or writing the same old boring Perl 5 OO code, and drooling over Perl 6 OO. So instead of switching to Ruby, I wrote Moose :)

        However audreyt mentions it in her Deploying Perl 6 talk and specifically writes:

        What is Moose?
        • Complete object model for Perl 5
        • Based on the Perl 6 object model
        • Production Ready