Miguel Prz
Miguel Prz

Reputation: 13792

Dynamic Moo object methods change

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?

Upvotes: 2

Views: 658

Answers (1)

Diab Jerius
Diab Jerius

Reputation: 2320

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.

Upvotes: 3

Related Questions