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