6 Moose::Cookbook::Roles::Recipe2 - Advanced Role Composition - method exclusion and aliasing
19 requires 'save_state', 'load_state';
25 package Restartable::ButUnreliable;
28 with 'Restartable' => {
38 $self->explode() if rand(1) > .5;
46 $self->explode() if rand(1) > .5;
51 package Restartable::ButBroken;
54 with 'Restartable' => { excludes => [ 'stop', 'start' ] };
70 In this example, we demonstrate how to exercise fine-grained control
71 over what methods we consume from a role. We have a C<Restartable>
72 role which provides an C<is_paused> attribute, and two methods,
75 Then we have two more roles which implement the same interface, each
76 putting their own spin on the C<stop> and C<start> methods.
78 In the C<Restartable::ButUnreliable> role, we want to provide a new
79 implementation of C<stop> and C<start>, but still have access to the
80 original implementation. To do this, we alias the methods from
81 C<Restartable> to private methods, and provide wrappers around the
84 with 'Restartable' => {
91 In the C<Restartable::ButBroken> role, we want to provide an entirely
92 new behavior for C<stop> and C<start>. We exclude them entirely when
93 composing the C<Restartable> role into C<Restartable::ButBroken>.
95 It's worth noting that the C<excludes> parameter also accepts a single
96 string as an argument if you just want to exclude one method.
98 with 'Restartable' => { excludes => [ 'stop', 'start' ] };
102 Exclusion and renaming are a power tool that can be handy, especially
103 when building roles out of other roles. In this example, all of our
104 roles implement the C<Restartable> role. Each role provides same API,
105 but each has a different implementation under the hood.
107 You can also use the method aliasing and excluding features when
108 composing a role into a class.
116 The mention of wrapper should tell you that we could do the same thing
117 using method modifiers, but for the sake of this example, we don't.
123 Dave Rolsky E<lt>autarch@urth.orgE<gt>
125 =head1 COPYRIGHT AND LICENSE
127 Copyright 2006-2009 by Infinity Interactive, Inc.
129 L<http://www.iinteractive.com>
131 This library is free software; you can redistribute it and/or modify
132 it under the same terms as Perl itself.
137 my $unreliable = Moose::Meta::Class->create_anon_class(
139 roles => [qw/Restartable::ButUnreliable/],
141 explode => sub { }, # nop.
142 'save_state' => sub { },
143 'load_state' => sub { },
146 ok( $unreliable, 'made anon class with Restartable::ButUnreliable role' );
147 can_ok( $unreliable, qw/start stop/ );
152 my $broken = Moose::Meta::Class->create_anon_class(
154 roles => [qw/Restartable::ButBroken/],
156 explode => sub { $cnt++ },
157 'save_state' => sub { },
158 'load_state' => sub { },
162 ok( $broken, 'made anon class with Restartable::ButBroken role' );
166 is( $cnt, 1, '... start called explode' );
170 is( $cnt, 2, '... stop also called explode' );