bump version
[gitmo/Role-Tiny.git] / lib / Role / Tiny.pm
CommitLineData
ab3370e7 1package Role::Tiny;
2
119014a7 3sub _getglob { \*{$_[0]} }
5e03b55c 4sub _getstash { \%{"$_[0]::"} }
119014a7 5
b1eebd55 6use strict;
7use warnings FATAL => 'all';
ab3370e7 8
e2722751 9our $VERSION = '1.000001'; # 1.0.1
c334a5c1 10$VERSION = eval $VERSION;
11
ab3370e7 12our %INFO;
13our %APPLIED_TO;
1947330a 14our %COMPOSED;
ab3370e7 15
cf62c989 16# Module state workaround totally stolen from Zefram's Module::Runtime.
17
18BEGIN {
19 *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
20}
21
22sub Role::Tiny::__GUARD__::DESTROY {
23 delete $INC{$_[0]->[0]} if @{$_[0]};
24}
5e03b55c 25
fb5074f6 26sub _load_module {
fb5074f6 27 (my $proto = $_[0]) =~ s/::/\//g;
cf62c989 28 $proto .= '.pm';
29 return 1 if $INC{$proto};
5e03b55c 30 # can't just ->can('can') because a sub-package Foo::Bar::Baz
31 # creates a 'Baz::' key in Foo::Bar's symbol table
32 return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
cf62c989 33 my $guard = _WORK_AROUND_BROKEN_MODULE_STATE
34 && bless([ $proto ], 'Role::Tiny::__GUARD__');
35 require $proto;
36 pop @$guard if _WORK_AROUND_BROKEN_MODULE_STATE;
fb5074f6 37 return 1;
38}
39
ab3370e7 40sub import {
41 my $target = caller;
a1164a0b 42 my $me = shift;
3ca7ff56 43 strict->import;
44 warnings->import(FATAL => 'all');
1ba11455 45 return if $INFO{$target}; # already exported into this package
ab3370e7 46 # get symbol table reference
47 my $stash = do { no strict 'refs'; \%{"${target}::"} };
48 # install before/after/around subs
49 foreach my $type (qw(before after around)) {
5a247406 50 *{_getglob "${target}::${type}"} = sub {
7568ba55 51 require Class::Method::Modifiers;
ab3370e7 52 push @{$INFO{$target}{modifiers}||=[]}, [ $type => @_ ];
53 };
54 }
5a247406 55 *{_getglob "${target}::requires"} = sub {
ab3370e7 56 push @{$INFO{$target}{requires}||=[]}, @_;
57 };
5a247406 58 *{_getglob "${target}::with"} = sub {
59 die "Only one role supported at a time by with" if @_ > 1;
369a4c50 60 $me->apply_role_to_package($target, $_[0]);
96d3f07a 61 };
7b8177f8 62 # grab all *non-constant* (stash slot is not a scalarref) subs present
ab3370e7 63 # in the symbol table and store their refaddrs (no need to forcibly
64 # inflate constant subs into real subs) - also add '' to here (this
65 # is used later)
66 @{$INFO{$target}{not_methods}={}}{
faa9ce11 67 '', map { *$_{CODE}||() } grep !ref($_), values %$stash
ab3370e7 68 } = ();
69 # a role does itself
70 $APPLIED_TO{$target} = { $target => undef };
71}
72
73sub apply_role_to_package {
369a4c50 74 my ($me, $to, $role) = @_;
1947330a 75
fb5074f6 76 _load_module($role);
77
ab3370e7 78 die "This is apply_role_to_package" if ref($to);
1947330a 79 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
80
81 $me->_check_requires($to, $role, @{$info->{requires}||[]});
82
83 $me->_install_methods($to, $role);
84
85 $me->_install_modifiers($to, $info->{modifiers});
86
87 # only add does() method to classes and only if they don't have one
88 if (not $INFO{$to} and not $to->can('does')) {
89 *{_getglob "${to}::does"} = \&does_role;
90 }
91
1947330a 92 # copy our role list into the target's
93 @{$APPLIED_TO{$to}||={}}{keys %{$APPLIED_TO{$role}}} = ();
94}
95
96sub apply_roles_to_object {
97 my ($me, $object, @roles) = @_;
98 die "No roles supplied!" unless @roles;
99 my $class = ref($object);
100 bless($object, $me->create_class_with_roles($class, @roles));
101 $object;
102}
103
104sub create_class_with_roles {
105 my ($me, $superclass, @roles) = @_;
106
fb5074f6 107 die "No roles supplied!" unless @roles;
108
c69190f1 109 my $new_name = join(
110 '__WITH__', $superclass, my $compose_name = join '__AND__', @roles
111 );
112
1947330a 113 return $new_name if $COMPOSED{class}{$new_name};
114
115 foreach my $role (@roles) {
fb5074f6 116 _load_module($role);
29dde8ba 117 die "${role} is not a Role::Tiny" unless $INFO{$role};
1947330a 118 }
119
786e5ba0 120 if ($] >= 5.010) {
7568ba55 121 require mro;
b1eebd55 122 } else {
7568ba55 123 require MRO::Compat;
b1eebd55 124 }
1947330a 125
126 my @composable = map $me->_composable_package_for($_), reverse @roles;
127
128 *{_getglob("${new_name}::ISA")} = [ @composable, $superclass ];
129
29dde8ba 130 my @info = map $INFO{$_}, @roles;
1947330a 131
132 $me->_check_requires(
133 $new_name, $compose_name,
134 do { my %h; @h{map @{$_->{requires}||[]}, @info} = (); keys %h }
135 );
1947330a 136
137 *{_getglob "${new_name}::does"} = \&does_role unless $new_name->can('does');
138
139 @{$APPLIED_TO{$new_name}||={}}{
140 map keys %{$APPLIED_TO{$_}}, @roles
141 } = ();
142
143 $COMPOSED{class}{$new_name} = 1;
144 return $new_name;
145}
146
147sub _composable_package_for {
148 my ($me, $role) = @_;
149 my $composed_name = 'Role::Tiny::_COMPOSABLE::'.$role;
150 return $composed_name if $COMPOSED{role}{$composed_name};
151 $me->_install_methods($composed_name, $role);
152 my $base_name = $composed_name.'::_BASE';
153 *{_getglob("${composed_name}::ISA")} = [ $base_name ];
154 my $modifiers = $INFO{$role}{modifiers}||[];
b1eebd55 155 my @mod_base;
1947330a 156 foreach my $modified (
157 do { my %h; @h{map $_->[1], @$modifiers} = (); keys %h }
158 ) {
b1eebd55 159 push @mod_base, "sub ${modified} { shift->next::method(\@_) }";
1947330a 160 }
385f5087 161 my $e;
59812c87 162 {
163 local $@;
164 eval(my $code = join "\n", "package ${base_name};", @mod_base);
385f5087 165 $e = "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
59812c87 166 }
385f5087 167 die $e if $e;
1947330a 168 $me->_install_modifiers($composed_name, $modifiers);
169 $COMPOSED{role}{$composed_name} = 1;
170 return $composed_name;
171}
172
173sub _check_requires {
174 my ($me, $to, $name, @requires) = @_;
175 if (my @requires_fail = grep !$to->can($_), @requires) {
176 # role -> role, add to requires, role -> class, error out
177 if (my $to_info = $INFO{$to}) {
178 push @{$to_info->{requires}||=[]}, @requires_fail;
179 } else {
180 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
181 }
182 }
183}
184
4db3a740 185sub _concrete_methods_of {
186 my ($me, $role) = @_;
1947330a 187 my $info = $INFO{$role};
4db3a740 188 $info->{methods} ||= do {
ab3370e7 189 # grab role symbol table
190 my $stash = do { no strict 'refs'; \%{"${role}::"}};
191 my $not_methods = $info->{not_methods};
192 +{
193 # grab all code entries that aren't in the not_methods list
194 map {
934ea2c1 195 my $code = *{$stash->{$_}}{CODE};
196 # rely on the '' key we added in import for "no code here"
197 exists $not_methods->{$code||''} ? () : ($_ => $code)
faa9ce11 198 } grep !ref($stash->{$_}), keys %$stash
ab3370e7 199 };
200 };
4db3a740 201}
202
203sub methods_provided_by {
204 my ($me, $role) = @_;
205 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
206 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
207}
208
209sub _install_methods {
210 my ($me, $to, $role) = @_;
211
212 my $info = $INFO{$role};
213
214 my $methods = $me->_concrete_methods_of($role);
1947330a 215
ab3370e7 216 # grab target symbol table
217 my $stash = do { no strict 'refs'; \%{"${to}::"}};
1947330a 218
ab3370e7 219 # determine already extant methods of target
220 my %has_methods;
221 @has_methods{grep
faa9ce11 222 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
ab3370e7 223 keys %$stash
224 } = ();
ab3370e7 225
1947330a 226 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
ab3370e7 227 no warnings 'once';
5a247406 228 *{_getglob "${to}::${i}"} = $methods->{$i};
ab3370e7 229 }
1947330a 230}
ab3370e7 231
1947330a 232sub _install_modifiers {
233 my ($me, $to, $modifiers) = @_;
dccea57d 234 if (my $info = $INFO{$to}) {
235 push @{$info->{modifiers}}, @{$modifiers||[]};
236 } else {
237 foreach my $modifier (@{$modifiers||[]}) {
238 $me->_install_single_modifier($to, @$modifier);
239 }
96d3f07a 240 }
ab3370e7 241}
242
dccea57d 243sub _install_single_modifier {
244 my ($me, @args) = @_;
245 Class::Method::Modifiers::install_modifier(@args);
246}
247
ab3370e7 248sub does_role {
390ac406 249 my ($proto, $role) = @_;
250 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
ab3370e7 251}
252
2531;
5febcf4d 254
0b6e5fff 255=head1 NAME
256
70061353 257Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
5febcf4d 258
259=head1 SYNOPSIS
260
261 package Some::Role;
262
263 use Role::Tiny;
264
265 sub foo { ... }
266
267 sub bar { ... }
268
adcb6c3d 269 around baz => sub { ... }
270
5febcf4d 271 1;
272
273else where
274
275 package Some::Class;
276
a1164a0b 277 use Role::Tiny::With;
5febcf4d 278
279 # bar gets imported, but not foo
a1164a0b 280 with 'Some::Role';
5febcf4d 281
282 sub foo { ... }
283
adcb6c3d 284 # baz is wrapped in the around modifier by Class::Method::Modifiers
285 sub baz { ... }
286
5febcf4d 287 1;
288
adcb6c3d 289If you wanted attributes as well, look at L<Moo::Role>.
290
5febcf4d 291=head1 DESCRIPTION
292
293C<Role::Tiny> is a minimalist role composition tool.
294
295=head1 ROLE COMPOSITION
296
297Role composition can be thought of as much more clever and meaningful multiple
298inheritance. The basics of this implementation of roles is:
299
300=over 2
301
302=item *
303
304If a method is already defined on a class, that method will not be composed in
305from the role.
306
307=item *
308
309If a method that the role L</requires> to be implemented is not implemented,
310role application will fail loudly.
311
0d39f9d3 312=back
313
5febcf4d 314Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
315composition is the other way around, where first wins. In a more complete
316system (see L<Moose>) roles are checked to see if they clash. The goal of this
317is to be much simpler, hence disallowing composition of multiple roles at once.
318
319=head1 METHODS
320
321=head2 apply_role_to_package
322
369a4c50 323 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
5febcf4d 324
a1164a0b 325Composes role with package. See also L<Role::Tiny::With>.
5febcf4d 326
327=head2 apply_roles_to_object
328
329 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
330
331Composes roles in order into object directly. Object is reblessed into the
332resulting class.
333
334=head2 create_class_with_roles
335
336 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
337
338Creates a new class based on base, with the roles composed into it in order.
339New class is returned.
340
54e4000d 341=head1 SUBROUTINES
5febcf4d 342
343=head2 does_role
344
54e4000d 345 if (Role::Tiny::does_role($foo, 'Some::Role')) {
5febcf4d 346 ...
347 }
348
349Returns true if class has been composed with role.
350
54e4000d 351This subroutine is also installed as ->does on any class a Role::Tiny is
352composed into unless that class already has an ->does method, so
353
e4aa82b1 354 if ($foo->does('Some::Role')) {
54e4000d 355 ...
356 }
357
358will work for classes but to test a role, one must use ::does_role directly
359
5febcf4d 360=head1 IMPORTED SUBROUTINES
361
362=head2 requires
363
364 requires qw(foo bar);
365
366Declares a list of methods that must be defined to compose role.
367
368=head2 with
369
370 with 'Some::Role1';
371 with 'Some::Role2';
372
373Composes another role into the current role. Only one role may be composed in
374at a time to allow the code to remain as simple as possible.
375
376=head2 before
377
378 before foo => sub { ... };
379
380See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
381documentation.
382
adcb6c3d 383Note that since you are not required to use method modifiers,
384L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
385a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
386both L<Class::Method::Modifiers> and L<Role::Tiny>.
387
5febcf4d 388=head2 around
389
390 around foo => sub { ... };
391
392See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
393documentation.
394
adcb6c3d 395Note that since you are not required to use method modifiers,
396L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
397a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
398both L<Class::Method::Modifiers> and L<Role::Tiny>.
399
5febcf4d 400=head2 after
401
402 after foo => sub { ... };
403
404See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
405documentation.
406
adcb6c3d 407Note that since you are not required to use method modifiers,
408L<Class::Method::Modifiers> is lazily loaded and we do not declare it as
409a dependency. If your L<Role::Tiny> role uses modifiers you must depend on
410both L<Class::Method::Modifiers> and L<Role::Tiny>.
411
412=head1 SEE ALSO
413
414L<Role::Tiny> is the attribute-less subset of L<Moo::Role>; L<Moo::Role> is
415a meta-protocol-less subset of the king of role systems, L<Moose::Role>.
416
417If you don't want method modifiers and do want to be forcibly restricted
418to a single role application per class, Ovid's L<Role::Basic> exists. But
419Stevan Little (the L<Moose> author) and I are both still convinced that
420he's Doing It Wrong.
421
c334a5c1 422=head1 AUTHOR
423
424mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
425
426=head1 CONTRIBUTORS
427
428dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
429
430frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
431
432hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
433
434jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
435
436ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
437
438chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
439
440ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
441
442doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
443
444perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
445
446=head1 COPYRIGHT
40f3e3aa 447
c334a5c1 448Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
449as listed above.
40f3e3aa 450
c334a5c1 451=head1 LICENSE
40f3e3aa 452
c334a5c1 453This library is free software and may be distributed under the same terms
454as perl itself.
40f3e3aa 455
456=cut