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