48e40b7be34f3530aa30a82a8be3d27923c8086a
[gitmo/Moose.git] / lib / Moose / Role.pm
1 package Moose::Role;
2 use strict;
3 use warnings;
4
5 use Scalar::Util 'blessed';
6 use Carp         'croak';
7 use Class::Load  'is_class_loaded';
8
9 use Sub::Exporter;
10
11 use Moose       ();
12 use Moose::Util ();
13
14 use Moose::Exporter;
15 use Moose::Meta::Role;
16 use Moose::Util::TypeConstraints;
17
18 sub extends {
19     croak "Roles do not support 'extends' (you can use 'with' to specialize a role)";
20 }
21
22 sub with {
23     Moose::Util::apply_all_roles( shift, @_ );
24 }
25
26 sub requires {
27     my $meta = shift;
28     croak "Must specify at least one method" unless @_;
29     $meta->add_required_methods(@_);
30 }
31
32 sub excludes {
33     my $meta = shift;
34     croak "Must specify at least one role" unless @_;
35     $meta->add_excluded_roles(@_);
36 }
37
38 sub has {
39     my $meta = shift;
40     my $name = shift;
41     croak 'Usage: has \'name\' => ( key => value, ... )' if @_ == 1;
42     my %options = ( definition_context => Moose::Util::_caller_info(), @_ );
43     my $attrs = ( ref($name) eq 'ARRAY' ) ? $name : [ ($name) ];
44     $meta->add_attribute( $_, %options ) for @$attrs;
45 }
46
47 sub _add_method_modifier {
48     my $type = shift;
49     my $meta = shift;
50
51     if ( ref($_[0]) eq 'Regexp' ) {
52         croak "Roles do not currently support regex "
53             . " references for $type method modifiers";
54     }
55
56     Moose::Util::add_method_modifier($meta, $type, \@_);
57 }
58
59 sub before { _add_method_modifier('before', @_) }
60
61 sub after  { _add_method_modifier('after',  @_) }
62
63 sub around { _add_method_modifier('around', @_) }
64
65 # see Moose.pm for discussion
66 sub super {
67     return unless $Moose::SUPER_BODY;
68     $Moose::SUPER_BODY->(@Moose::SUPER_ARGS);
69 }
70
71 sub override {
72     my $meta = shift;
73     my ( $name, $code ) = @_;
74     $meta->add_override_method_modifier( $name, $code );
75 }
76
77 sub inner {
78     croak "Roles cannot support 'inner'";
79 }
80
81 sub augment {
82     croak "Roles cannot support 'augment'";
83 }
84
85 Moose::Exporter->setup_import_methods(
86     with_meta => [
87         qw( with requires excludes has before after around override )
88     ],
89     as_is => [
90         qw( extends super inner augment ),
91         \&Carp::confess,
92         \&Scalar::Util::blessed,
93     ],
94 );
95
96 sub init_meta {
97     shift;
98     my %args = @_;
99
100     my $role = $args{for_class};
101
102     unless ($role) {
103         require Moose;
104         Moose->throw_error("Cannot call init_meta without specifying a for_class");
105     }
106
107     my $metaclass = $args{metaclass} || "Moose::Meta::Role";
108     my $meta_name = exists $args{meta_name} ? $args{meta_name} : 'meta';
109
110     Moose->throw_error("The Metaclass $metaclass must be loaded. (Perhaps you forgot to 'use $metaclass'?)")
111         unless is_class_loaded($metaclass);
112
113     Moose->throw_error("The Metaclass $metaclass must be a subclass of Moose::Meta::Role.")
114         unless $metaclass->isa('Moose::Meta::Role');
115
116     # make a subtype for each Moose role
117     role_type $role unless find_type_constraint($role);
118
119     my $meta;
120     if ( $meta = Class::MOP::get_metaclass_by_name($role) ) {
121         unless ( $meta->isa("Moose::Meta::Role") ) {
122             my $error_message = "$role already has a metaclass, but it does not inherit $metaclass ($meta).";
123             if ( $meta->isa('Moose::Meta::Class') ) {
124                 Moose->throw_error($error_message . ' You cannot make the same thing a role and a class. Remove either Moose or Moose::Role.');
125             } else {
126                 Moose->throw_error($error_message);
127             }
128         }
129     }
130     else {
131         $meta = $metaclass->initialize($role);
132     }
133
134     if (defined $meta_name) {
135         # also check for inherited non moose 'meta' method?
136         my $existing = $meta->get_method($meta_name);
137         if ($existing && !$existing->isa('Class::MOP::Method::Meta')) {
138             Carp::cluck "Moose::Role is overwriting an existing method named "
139                       . "$meta_name in role $role with a method "
140                       . "which returns the class's metaclass. If this is "
141                       . "actually what you want, you should remove the "
142                       . "existing method, otherwise, you should rename or "
143                       . "disable this generated method using the "
144                       . "'-meta_name' option to 'use Moose::Role'.";
145         }
146         $meta->_add_meta_method($meta_name);
147     }
148
149     return $meta;
150 }
151
152 1;
153
154 # ABSTRACT: The Moose Role
155
156 __END__
157
158 =pod
159
160 =head1 SYNOPSIS
161
162   package Eq;
163   use Moose::Role; # automatically turns on strict and warnings
164
165   requires 'equal';
166
167   sub no_equal {
168       my ($self, $other) = @_;
169       !$self->equal($other);
170   }
171
172   # ... then in your classes
173
174   package Currency;
175   use Moose; # automatically turns on strict and warnings
176
177   with 'Eq';
178
179   sub equal {
180       my ($self, $other) = @_;
181       $self->as_float == $other->as_float;
182   }
183
184   # ... and also
185
186   package Comparator;
187   use Moose;
188
189   has compare_to => (
190       is      => 'ro',
191       does    => 'Eq',
192       handles => 'Eq',
193   );
194
195   # ... which allows
196
197   my $currency1 = Currency->new(...);
198   my $currency2 = Currency->new(...);
199   Comparator->new(compare_to => $currency1)->equal($currency2);
200
201 =head1 DESCRIPTION
202
203 The concept of roles is documented in L<Moose::Manual::Roles>. This document
204 serves as API documentation.
205
206 =head1 EXPORTED FUNCTIONS
207
208 Moose::Role currently supports all of the functions that L<Moose> exports, but
209 differs slightly in how some items are handled (see L</CAVEATS> below for
210 details).
211
212 Moose::Role also offers two role-specific keyword exports:
213
214 =over 4
215
216 =item B<requires (@method_names)>
217
218 Roles can require that certain methods are implemented by any class which
219 C<does> the role.
220
221 Note that attribute accessors also count as methods for the purposes
222 of satisfying the requirements of a role.
223
224 =item B<excludes (@role_names)>
225
226 Roles can C<exclude> other roles, in effect saying "I can never be combined
227 with these C<@role_names>". This is a feature which should not be used
228 lightly.
229
230 =back
231
232 =head2 B<unimport>
233
234 Moose::Role offers a way to remove the keywords it exports, through the
235 C<unimport> method. You simply have to say C<no Moose::Role> at the bottom of
236 your code for this to work.
237
238 =head1 METACLASS
239
240 When you use Moose::Role, you can specify traits which will be applied to your
241 role metaclass:
242
243     use Moose::Role -traits => 'My::Trait';
244
245 This is very similar to the attribute traits feature. When you do
246 this, your class's C<meta> object will have the specified traits
247 applied to it. See L<Moose/Metaclass and Trait Name Resolution> for more
248 details.
249
250 =head1 APPLYING ROLES
251
252 In addition to being applied to a class using the 'with' syntax (see
253 L<Moose::Manual::Roles>) and using the L<Moose::Util> 'apply_all_roles'
254 method, roles may also be applied to an instance of a class using
255 L<Moose::Util> 'apply_all_roles' or the role's metaclass:
256
257    MyApp::Test::SomeRole->meta->apply( $instance );
258
259 Doing this creates a new, mutable, anonymous subclass, applies the role to that,
260 and reblesses. In a debugger, for example, you will see class names of the
261 form C< Moose::Meta::Class::__ANON__::SERIAL::6 >, which means that doing a
262 'ref' on your instance may not return what you expect. See L<Moose::Object> for
263 'DOES'.
264
265 Additional params may be added to the new instance by providing
266 'rebless_params'. See L<Moose::Meta::Role::Application::ToInstance>.
267
268 =head1 CAVEATS
269
270 Role support has only a few caveats:
271
272 =over 4
273
274 =item *
275
276 Roles cannot use the C<extends> keyword; it will throw an exception for now.
277 The same is true of the C<augment> and C<inner> keywords (not sure those
278 really make sense for roles). All other Moose keywords will be I<deferred>
279 so that they can be applied to the consuming class.
280
281 =item *
282
283 Role composition does its best to B<not> be order-sensitive when it comes to
284 conflict resolution and requirements detection. However, it is order-sensitive
285 when it comes to method modifiers. All before/around/after modifiers are
286 included whenever a role is composed into a class, and then applied in the order
287 in which the roles are used. This also means that there is no conflict for
288 before/around/after modifiers.
289
290 In most cases, this will be a non-issue; however, it is something to keep in
291 mind when using method modifiers in a role. You should never assume any
292 ordering.
293
294 =back
295
296 =head1 BUGS
297
298 See L<Moose/BUGS> for details on reporting bugs.
299
300 =cut