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