Apply a role to a Moose object

You can apply a role to a Moose object. You can do something like

#!/usr/bin/perl -w
use strict;
use feature ':5.10';

package foo;
use Moose::Role;
sub baz { say 'i can haz baz'; }

package bar;
use Moose;
1;

package main;
my $test = bar->new;
say "i can't haz baz" if !$test->can("baz");
foo->meta->apply($test);
$test->baz;

with the following output

 i can't haz baz
 i can haz baz

 use strict;
 use feature ':5.10';

 package foo;
 use Moose::Role;
 sub baz { say 'i can haz baz'; }

 package bar;
 use Moose;
 sub apply_a_role { my ($self, $role) = @_; $role->meta->apply($self); }
 1;

 my $test = bar->new;
 say "i can't haz baz" if !$test->can("baz");
 $test2->apply_a_role('foo');
 $test2->baz;

With the same results .

By: franck on 2009-07-26T18:36:14

Tags: moose

permalink