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