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