correct typo in abstract
[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
c334a5c1 9our $VERSION = '1.000000'; # 1.0.0
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 }
59812c87 161 {
162 local $@;
163 eval(my $code = join "\n", "package ${base_name};", @mod_base);
164 die "Evaling failed: $@\nTrying to eval:\n${code}" if $@;
165 }
1947330a 166 $me->_install_modifiers($composed_name, $modifiers);
167 $COMPOSED{role}{$composed_name} = 1;
168 return $composed_name;
169}
170
171sub _check_requires {
172 my ($me, $to, $name, @requires) = @_;
173 if (my @requires_fail = grep !$to->can($_), @requires) {
174 # role -> role, add to requires, role -> class, error out
175 if (my $to_info = $INFO{$to}) {
176 push @{$to_info->{requires}||=[]}, @requires_fail;
177 } else {
178 die "Can't apply ${name} to ${to} - missing ".join(', ', @requires_fail);
179 }
180 }
181}
182
4db3a740 183sub _concrete_methods_of {
184 my ($me, $role) = @_;
1947330a 185 my $info = $INFO{$role};
4db3a740 186 $info->{methods} ||= do {
ab3370e7 187 # grab role symbol table
188 my $stash = do { no strict 'refs'; \%{"${role}::"}};
189 my $not_methods = $info->{not_methods};
190 +{
191 # grab all code entries that aren't in the not_methods list
192 map {
934ea2c1 193 my $code = *{$stash->{$_}}{CODE};
194 # rely on the '' key we added in import for "no code here"
195 exists $not_methods->{$code||''} ? () : ($_ => $code)
faa9ce11 196 } grep !ref($stash->{$_}), keys %$stash
ab3370e7 197 };
198 };
4db3a740 199}
200
201sub methods_provided_by {
202 my ($me, $role) = @_;
203 die "${role} is not a Role::Tiny" unless my $info = $INFO{$role};
204 (keys %{$me->_concrete_methods_of($role)}, @{$info->{requires}||[]});
205}
206
207sub _install_methods {
208 my ($me, $to, $role) = @_;
209
210 my $info = $INFO{$role};
211
212 my $methods = $me->_concrete_methods_of($role);
1947330a 213
ab3370e7 214 # grab target symbol table
215 my $stash = do { no strict 'refs'; \%{"${to}::"}};
1947330a 216
ab3370e7 217 # determine already extant methods of target
218 my %has_methods;
219 @has_methods{grep
faa9ce11 220 +(ref($stash->{$_}) || *{$stash->{$_}}{CODE}),
ab3370e7 221 keys %$stash
222 } = ();
ab3370e7 223
1947330a 224 foreach my $i (grep !exists $has_methods{$_}, keys %$methods) {
ab3370e7 225 no warnings 'once';
5a247406 226 *{_getglob "${to}::${i}"} = $methods->{$i};
ab3370e7 227 }
1947330a 228}
ab3370e7 229
1947330a 230sub _install_modifiers {
231 my ($me, $to, $modifiers) = @_;
dccea57d 232 if (my $info = $INFO{$to}) {
233 push @{$info->{modifiers}}, @{$modifiers||[]};
234 } else {
235 foreach my $modifier (@{$modifiers||[]}) {
236 $me->_install_single_modifier($to, @$modifier);
237 }
96d3f07a 238 }
ab3370e7 239}
240
dccea57d 241sub _install_single_modifier {
242 my ($me, @args) = @_;
243 Class::Method::Modifiers::install_modifier(@args);
244}
245
ab3370e7 246sub does_role {
390ac406 247 my ($proto, $role) = @_;
248 return exists $APPLIED_TO{ref($proto)||$proto}{$role};
ab3370e7 249}
250
2511;
5febcf4d 252
0b6e5fff 253=head1 NAME
254
70061353 255Role::Tiny - Roles. Like a nouvelle cuisine portion size slice of Moose.
5febcf4d 256
257=head1 SYNOPSIS
258
259 package Some::Role;
260
261 use Role::Tiny;
262
263 sub foo { ... }
264
265 sub bar { ... }
266
267 1;
268
269else where
270
271 package Some::Class;
272
a1164a0b 273 use Role::Tiny::With;
5febcf4d 274
275 # bar gets imported, but not foo
a1164a0b 276 with 'Some::Role';
5febcf4d 277
278 sub foo { ... }
279
280 1;
281
282=head1 DESCRIPTION
283
284C<Role::Tiny> is a minimalist role composition tool.
285
286=head1 ROLE COMPOSITION
287
288Role composition can be thought of as much more clever and meaningful multiple
289inheritance. The basics of this implementation of roles is:
290
291=over 2
292
293=item *
294
295If a method is already defined on a class, that method will not be composed in
296from the role.
297
298=item *
299
300If a method that the role L</requires> to be implemented is not implemented,
301role application will fail loudly.
302
0d39f9d3 303=back
304
5febcf4d 305Unlike L<Class::C3>, where the B<last> class inherited from "wins," role
306composition is the other way around, where first wins. In a more complete
307system (see L<Moose>) roles are checked to see if they clash. The goal of this
308is to be much simpler, hence disallowing composition of multiple roles at once.
309
310=head1 METHODS
311
312=head2 apply_role_to_package
313
369a4c50 314 Role::Tiny->apply_role_to_package('Some::Package', 'Some::Role');
5febcf4d 315
a1164a0b 316Composes role with package. See also L<Role::Tiny::With>.
5febcf4d 317
318=head2 apply_roles_to_object
319
320 Role::Tiny->apply_roles_to_object($foo, qw(Some::Role1 Some::Role2));
321
322Composes roles in order into object directly. Object is reblessed into the
323resulting class.
324
325=head2 create_class_with_roles
326
327 Role::Tiny->create_class_with_roles('Some::Base', qw(Some::Role1 Some::Role2));
328
329Creates a new class based on base, with the roles composed into it in order.
330New class is returned.
331
54e4000d 332=head1 SUBROUTINES
5febcf4d 333
334=head2 does_role
335
54e4000d 336 if (Role::Tiny::does_role($foo, 'Some::Role')) {
5febcf4d 337 ...
338 }
339
340Returns true if class has been composed with role.
341
54e4000d 342This subroutine is also installed as ->does on any class a Role::Tiny is
343composed into unless that class already has an ->does method, so
344
e4aa82b1 345 if ($foo->does('Some::Role')) {
54e4000d 346 ...
347 }
348
349will work for classes but to test a role, one must use ::does_role directly
350
5febcf4d 351=head1 IMPORTED SUBROUTINES
352
353=head2 requires
354
355 requires qw(foo bar);
356
357Declares a list of methods that must be defined to compose role.
358
359=head2 with
360
361 with 'Some::Role1';
362 with 'Some::Role2';
363
364Composes another role into the current role. Only one role may be composed in
365at a time to allow the code to remain as simple as possible.
366
367=head2 before
368
369 before foo => sub { ... };
370
371See L<< Class::Method::Modifiers/before method(s) => sub { ... } >> for full
372documentation.
373
374=head2 around
375
376 around foo => sub { ... };
377
378See L<< Class::Method::Modifiers/around method(s) => sub { ... } >> for full
379documentation.
380
381=head2 after
382
383 after foo => sub { ... };
384
385See L<< Class::Method::Modifiers/after method(s) => sub { ... } >> for full
386documentation.
387
c334a5c1 388=head1 AUTHOR
389
390mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
391
392=head1 CONTRIBUTORS
393
394dg - David Leadbeater (cpan:DGL) <dgl@dgl.cx>
395
396frew - Arthur Axel "fREW" Schmidt (cpan:FREW) <frioux@gmail.com>
397
398hobbs - Andrew Rodland (cpan:ARODLAND) <arodland@cpan.org>
399
400jnap - John Napiorkowski (cpan:JJNAPIORK) <jjn1056@yahoo.com>
401
402ribasushi - Peter Rabbitson (cpan:RIBASUSHI) <ribasushi@cpan.org>
403
404chip - Chip Salzenberg (cpan:CHIPS) <chip@pobox.com>
405
406ajgb - Alex J. G. BurzyƄski (cpan:AJGB) <ajgb@cpan.org>
407
408doy - Jesse Luehrs (cpan:DOY) <doy at tozt dot net>
409
410perigrin - Chris Prather (cpan:PERIGRIN) <chris@prather.org>
411
412=head1 COPYRIGHT
40f3e3aa 413
c334a5c1 414Copyright (c) 2010-2012 the Role::Tiny L</AUTHOR> and L</CONTRIBUTORS>
415as listed above.
40f3e3aa 416
c334a5c1 417=head1 LICENSE
40f3e3aa 418
c334a5c1 419This library is free software and may be distributed under the same terms
420as perl itself.
40f3e3aa 421
422=cut