Lazy load Mouse::Meta::Role
[gitmo/Mouse.git] / lib / Mouse.pm
1 package Mouse;
2 use 5.006_002;
3
4 use Mouse::Exporter; # enables strict and warnings
5
6 our $VERSION = '0.40';
7
8 use Carp         qw(confess);
9 use Scalar::Util qw(blessed);
10
11 use Mouse::Util qw(load_class is_class_loaded get_code_package not_supported);
12
13 use Mouse::Meta::Module;
14 use Mouse::Meta::Class;
15 use Mouse::Meta::Attribute;
16 use Mouse::Object;
17 use Mouse::Util::TypeConstraints ();
18
19 Mouse::Exporter->setup_import_methods(
20     as_is => [qw(
21         extends with
22         has
23         before after around
24         override super
25         augment  inner
26     ),
27         \&Scalar::Util::blessed,
28         \&Carp::confess,
29    ],
30 );
31
32 # XXX: for backward compatibility
33 our @EXPORT = qw(
34     extends with
35     has
36     before after around
37     override super
38     augment  inner
39     blessed confess
40 );
41
42 sub extends { Mouse::Meta::Class->initialize(scalar caller)->superclasses(@_) }
43
44 sub has {
45     my $meta = Mouse::Meta::Class->initialize(scalar caller);
46     my $name = shift;
47
48     $meta->throw_error(q{Usage: has 'name' => ( key => value, ... )})\r
49         if @_ % 2; # odd number of arguments
50
51     $meta->add_attribute($_ => @_) for ref($name) ? @{$name} : $name;
52 }
53
54 sub before {
55     my $meta = Mouse::Meta::Class->initialize(scalar caller);
56
57     my $code = pop;
58
59     for (@_) {
60         $meta->add_before_method_modifier($_ => $code);
61     }
62 }
63
64 sub after {
65     my $meta = Mouse::Meta::Class->initialize(scalar caller);
66
67     my $code = pop;
68
69     for (@_) {
70         $meta->add_after_method_modifier($_ => $code);
71     }
72 }
73
74 sub around {
75     my $meta = Mouse::Meta::Class->initialize(scalar caller);
76
77     my $code = pop;
78
79     for (@_) {
80         $meta->add_around_method_modifier($_ => $code);
81     }
82 }
83
84 sub with {
85     Mouse::Util::apply_all_roles(scalar(caller), @_);
86 }
87
88 our $SUPER_PACKAGE;
89 our $SUPER_BODY;
90 our @SUPER_ARGS;
91
92 sub super {
93     # This check avoids a recursion loop - see
94     # t/100_bugs/020_super_recursion.t
95     return if  defined $SUPER_PACKAGE && $SUPER_PACKAGE ne caller();
96     return if !defined $SUPER_BODY;
97     $SUPER_BODY->(@SUPER_ARGS);
98 }
99
100 sub override {
101     # my($name, $method) = @_;
102     Mouse::Meta::Class->initialize(scalar caller)->add_override_method_modifier(@_);
103 }
104
105 our %INNER_BODY;
106 our %INNER_ARGS;
107
108 sub inner {
109     my $pkg = caller();
110     if ( my $body = $INNER_BODY{$pkg} ) {
111         my $args = $INNER_ARGS{$pkg};
112         local $INNER_ARGS{$pkg};
113         local $INNER_BODY{$pkg};
114         return $body->(@{$args});
115     }
116     else {
117         return;
118     }
119 }
120
121 sub augment {
122     #my($name, $method) = @_;
123     Mouse::Meta::Class->initialize(scalar caller)->add_augment_method_modifier(@_);
124 }
125
126 sub init_meta {
127     shift;
128     my %args = @_;
129
130     my $class = $args{for_class}
131                     or confess("Cannot call init_meta without specifying a for_class");
132
133     my $base_class = $args{base_class} || 'Mouse::Object';
134     my $metaclass  = $args{metaclass}  || 'Mouse::Meta::Class';
135
136     my $meta = $metaclass->initialize($class);
137
138     $meta->add_method(meta => sub{
139         return $metaclass->initialize(ref($_[0]) || $_[0]);
140     });
141
142     $meta->superclasses($base_class)
143         unless $meta->superclasses;
144
145     # make a class type for each Mouse class
146     Mouse::Util::TypeConstraints::class_type($class)
147         unless Mouse::Util::TypeConstraints::find_type_constraint($class);
148
149     return $meta;
150 }
151
152
153 1;
154 __END__
155
156 =head1 NAME
157
158 Mouse - Moose minus the antlers
159
160 =head1 VERSION
161
162 This document describes Mouse version 0.40
163
164 =head1 SYNOPSIS
165
166     package Point;
167     use Mouse; # automatically turns on strict and warnings
168
169     has 'x' => (is => 'rw', isa => 'Int');
170     has 'y' => (is => 'rw', isa => 'Int');
171
172     sub clear {
173         my $self = shift;
174         $self->x(0);
175         $self->y(0);
176     }
177
178     package Point3D;
179     use Mouse;
180
181     extends 'Point';
182
183     has 'z' => (is => 'rw', isa => 'Int');
184
185     after 'clear' => sub {
186         my $self = shift;
187         $self->z(0);
188     };
189
190 =head1 DESCRIPTION
191
192 L<Moose> is wonderful. B<Use Moose instead of Mouse.>
193
194 Unfortunately, Moose has a compile-time penalty. Though significant progress
195 has been made over the years, the compile time penalty is a non-starter for
196 some very specific applications. If you are writing a command-line application
197 or CGI script where startup time is essential, you may not be able to use
198 Moose. We recommend that you instead use L<HTTP::Engine> and FastCGI for the
199 latter, if possible.
200
201 Mouse aims to alleviate this by providing a subset of Moose's functionality,
202 faster.
203
204 We're also going as light on dependencies as possible. Mouse currently has
205 B<no dependencies> except for testing modules.
206
207 =head2 MOOSE COMPATIBILITY
208
209 Compatibility with Moose has been the utmost concern. Fewer than 1% of the
210 tests fail when run against Moose instead of Mouse. Mouse code coverage is also
211 over 96%. Even the error messages are taken from Moose. The Mouse code just
212 runs the test suite 4x faster.
213
214 The idea is that, if you need the extra power, you should be able to run
215 C<s/Mouse/Moose/g> on your codebase and have nothing break. To that end,
216 we have written L<Any::Moose> which will act as Mouse unless Moose is loaded,
217 in which case it will act as Moose. Since Mouse is a little sloppier than
218 Moose, if you run into weird errors, it would be worth running:
219
220     ANY_MOOSE=Moose perl your-script.pl
221
222 to see if the bug is caused by Mouse. Moose's diagnostics and validation are
223 also much better.
224
225 See also L<Mouse::Spec> for compatibility and incompatibility with Moose.
226
227 =head2 MouseX
228
229 Please don't copy MooseX code to MouseX. If you need extensions, you really
230 should upgrade to Moose. We don't need two parallel sets of extensions!
231
232 If you really must write a Mouse extension, please contact the Moose mailing
233 list or #moose on IRC beforehand.
234
235 =head1 KEYWORDS
236
237 =head2 C<< $object->meta -> Mouse::Meta::Class >>
238
239 Returns this class' metaclass instance.
240
241 =head2 C<< extends superclasses >>
242
243 Sets this class' superclasses.
244
245 =head2 C<< before (method|methods) => CodeRef >>
246
247 Installs a "before" method modifier. See L<Moose/before> or
248 L<Class::Method::Modifiers/before>.
249
250 Use of this feature requires L<Class::Method::Modifiers>!
251
252 =head2 C<< after (method|methods) => CodeRef >>
253
254 Installs an "after" method modifier. See L<Moose/after> or
255 L<Class::Method::Modifiers/after>.
256
257 Use of this feature requires L<Class::Method::Modifiers>!
258
259 =head2 C<< around (method|methods) => CodeRef >>
260
261 Installs an "around" method modifier. See L<Moose/around> or
262 L<Class::Method::Modifiers/around>.
263
264 Use of this feature requires L<Class::Method::Modifiers>!
265
266 =head2 C<< has (name|names) => parameters >>
267
268 Adds an attribute (or if passed an arrayref of names, multiple attributes) to
269 this class. Options:
270
271 =over 4
272
273 =item C<< is => ro|rw|bare >>
274
275 If specified, inlines a read-only/read-write accessor with the same name as
276 the attribute.
277
278 =item C<< isa => TypeConstraint >>
279
280 Provides type checking in the constructor and accessor. The following types are
281 supported. Any unknown type is taken to be a class check
282 (e.g. C<< isa => 'DateTime' >> would accept only L<DateTime> objects).
283
284     Any Item Bool Undef Defined Value Num Int Str ClassName
285     Ref ScalarRef ArrayRef HashRef CodeRef RegexpRef GlobRef
286     FileHandle Object
287
288 For more documentation on type constraints, see L<Mouse::Util::TypeConstraints>.
289
290
291 =item C<< required => Bool >>
292
293 Whether this attribute is required to have a value. If the attribute is lazy or
294 has a builder, then providing a value for the attribute in the constructor is
295 optional.
296
297 =item C<< init_arg => Str | Undef >>
298
299 Allows you to use a different key name in the constructor.  If undef, the
300 attribute can't be passed to the constructor.
301
302 =item C<< default => Value | CodeRef >>
303
304 Sets the default value of the attribute. If the default is a coderef, it will
305 be invoked to get the default value. Due to quirks of Perl, any bare reference
306 is forbidden, you must wrap the reference in a coderef. Otherwise, all
307 instances will share the same reference.
308
309 =item C<< lazy => Bool >>
310
311 If specified, the default is calculated on demand instead of in the
312 constructor.
313
314 =item C<< predicate => Str >>
315
316 Lets you specify a method name for installing a predicate method, which checks
317 that the attribute has a value. It will not invoke a lazy default or builder
318 method.
319
320 =item C<< clearer => Str >>
321
322 Lets you specify a method name for installing a clearer method, which clears
323 the attribute's value from the instance. On the next read, lazy or builder will
324 be invoked.
325
326 =item C<< handles => HashRef|ArrayRef >>
327
328 Lets you specify methods to delegate to the attribute. ArrayRef forwards the
329 given method names to method calls on the attribute. HashRef maps local method
330 names to remote method names called on the attribute. Other forms of
331 L</handles>, such as regular expression and coderef, are not yet supported.
332
333 =item C<< weak_ref => Bool >>
334
335 Lets you automatically weaken any reference stored in the attribute.
336
337 Use of this feature requires L<Scalar::Util>!
338
339 =item C<< trigger => CodeRef >>
340
341 Any time the attribute's value is set (either through the accessor or the constructor), the trigger is called on it. The trigger receives as arguments the instance, the new value, and the attribute instance.
342
343 =item C<< builder => Str >>
344
345 Defines a method name to be called to provide the default value of the
346 attribute. C<< builder => 'build_foo' >> is mostly equivalent to
347 C<< default => sub { $_[0]->build_foo } >>.
348
349 =item C<< auto_deref => Bool >>
350
351 Allows you to automatically dereference ArrayRef and HashRef attributes in list
352 context. In scalar context, the reference is returned (NOT the list length or
353 bucket status). You must specify an appropriate type constraint to use
354 auto_deref.
355
356 =item C<< lazy_build => Bool >>
357
358 Automatically define the following options:
359
360     has $attr => (
361         # ...
362         lazy      => 1
363         builder   => "_build_$attr",
364         clearer   => "clear_$attr",
365         predicate => "has_$attr",
366     );
367
368 =back
369
370 =head2 C<< confess(message) -> BOOM >>
371
372 L<Carp/confess> for your convenience.
373
374 =head2 C<< blessed(value) -> ClassName | undef >>
375
376 L<Scalar::Util/blessed> for your convenience.
377
378 =head1 MISC
379
380 =head2 import
381
382 Importing Mouse will default your class' superclass list to L<Mouse::Object>.
383 You may use L</extends> to replace the superclass list.
384
385 =head2 unimport
386
387 Please unimport Mouse (C<no Mouse>) so that if someone calls one of the
388 keywords (such as L</extends>) it will break loudly instead breaking subtly.
389
390 =head1 SOURCE CODE ACCESS
391
392 We have a public git repository:
393
394  git clone git://jules.scsys.co.uk/gitmo/Mouse.git
395
396 =head1 DEPENDENCIES
397
398 Perl 5.6.2 or later.
399
400 =head1 SEE ALSO
401
402 L<Mouse::Spec>
403
404 L<Moose>
405
406 L<Class::MOP>
407
408 =head1 AUTHORS
409
410 Shawn M Moore, E<lt>sartak at gmail.comE<gt>
411
412 Yuval Kogman, E<lt>nothingmuch at woobling.orgE<gt>
413
414 tokuhirom
415
416 Yappo
417
418 wu-lee
419
420 Goro Fuji (gfx) E<lt>gfuji at cpan.orgE<gt>
421
422 with plenty of code borrowed from L<Class::MOP> and L<Moose>
423
424 =head1 BUGS
425
426 All complex software has bugs lurking in it, and this module is no exception.
427 Please report any bugs to C<bug-mouse at rt.cpan.org>, or through the web
428 interface at L<http://rt.cpan.org/Public/Dist/Display.html?Name=Mouse>
429
430 =head1 COPYRIGHT AND LICENSE
431
432 Copyright 2008-2009 Infinity Interactive, Inc.
433
434 http://www.iinteractive.com/
435
436 This program is free software; you can redistribute it and/or modify it
437 under the same terms as Perl itself.
438
439 =cut
440