2

I am using Moo as my OO engine, and I want to change the behaviour of some instances at runtime. I need to add new methods and change the existing ones.

Is that possible with Moo? If not, how can I achieve this?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Miguel Prz
  • 13,718
  • 29
  • 42
  • 2
    I've always assumed this is the dividing line between Moo and Moose. Once you want to start fiddling with meta-objects you want Moose. Be interesting to see if there's something I've missed though. – Richard Huxton Jun 11 '13 at 08:37

1 Answers1

3

You can do this using Moo:Role (see also Role::Tiny and Class::Method::Modifiers for details). For example:

use 5.10.1;

package Foo {
    use Moo;
    has a => ( is => 'rw' );
    sub m1 { return "m1" }
}

package Foo::Role {

    use Moo::Role;

    sub m2 { return "m2" }

    around 'm1' => sub {
        # original Foo::m1
        my $orig = shift;
        return "wrapped: " . $orig->(@_);
    }
}

use Role::Tiny;

my $foo = Foo->new;
say $foo->m1;
Role::Tiny->apply_roles_to_object( $foo, 'Foo::Role' );
say $foo->m2;
say $foo->m1;

my $boo = Foo->new;

say $boo->m1;
say $boo->m2;

You get:

m1
m2
wrapped: m1
m1
Can't locate object method "m2" via package "Foo" at moo.pm line 49.
Diab Jerius
  • 2,310
  • 13
  • 18