0.13 and 0.14 Changes
[gitmo/Mouse.git] / lib / Mouse.pm
CommitLineData
c3398f5b 1package Mouse;
2use strict;
3use warnings;
eae80759 4use 5.006;
eaad7dab 5use base 'Exporter';
c3398f5b 6
4216fc14 7our $VERSION = '0.14';
126765f0 8use 5.006;
c3398f5b 9
eae80759 10BEGIN {
eae80759 11 if ($ENV{MOUSE_DEBUG}) {
12 *DEBUG = sub (){ 1 };
13 } else {
14 *DEBUG = sub (){ 0 };
15 }
11ac534b 16}
17
c3398f5b 18use Carp 'confess';
6c169c50 19use Scalar::Util 'blessed';
20use Mouse::Util;
c3398f5b 21
306290e8 22use Mouse::Meta::Attribute;
23use Mouse::Meta::Class;
c3398f5b 24use Mouse::Object;
d60c78b9 25use Mouse::TypeRegistry;
c3398f5b 26
eaad7dab 27our @EXPORT = qw(extends has before after around blessed confess with);
28
29sub extends { Mouse::Meta::Class->initialize(caller)->superclasses(@_) }
c3398f5b 30
eaad7dab 31sub has {
32 my $meta = Mouse::Meta::Class->initialize(caller);
c3398f5b 33
eaad7dab 34 my $names = shift;
35 $names = [$names] if !ref($names);
36
37 for my $name (@$names) {
38 if ($name =~ s/^\+//) {
39 Mouse::Meta::Attribute->clone_parent($meta, $name, @_);
40 }
41 else {
42 Mouse::Meta::Attribute->create($meta, $name, @_);
c3398f5b 43 }
44 }
eaad7dab 45}
46
47sub before {
48 my $meta = Mouse::Meta::Class->initialize(caller);
49
50 my $code = pop;
51
52 for (@_) {
53 $meta->add_before_method_modifier($_ => $code);
54 }
55}
56
57sub after {
58 my $meta = Mouse::Meta::Class->initialize(caller);
59
60 my $code = pop;
61
62 for (@_) {
63 $meta->add_after_method_modifier($_ => $code);
64 }
65}
66
67sub around {
68 my $meta = Mouse::Meta::Class->initialize(caller);
69
70 my $code = pop;
71
72 for (@_) {
73 $meta->add_around_method_modifier($_ => $code);
74 }
75}
76
77sub with {
21498b08 78 Mouse::Util::apply_all_roles((caller)[0], @_);
eaad7dab 79}
80
81sub import {
e15d73d2 82 my $class = shift;
83
eaad7dab 84 strict->import;
85 warnings->import;
86
87 my $caller = caller;
88
89 my $meta = Mouse::Meta::Class->initialize($caller);
90 $meta->superclasses('Mouse::Object')
91 unless $meta->superclasses;
92
93 no strict 'refs';
94 no warnings 'redefine';
95 *{$caller.'::meta'} = sub { $meta };
96
e15d73d2 97 if (@_) {
98 __PACKAGE__->export_to_level( 1, $class, @_);
99 } else {
100 # shortcut for the common case of no type character
101 no strict 'refs';
102 for my $keyword (@EXPORT) {
103 *{ $caller . '::' . $keyword } = *{__PACKAGE__ . '::' . $keyword};
104 }
105 }
eaad7dab 106}
107
108sub unimport {
109 my $caller = caller;
110
111 no strict 'refs';
112 for my $keyword (@EXPORT) {
113 delete ${ $caller . '::' }{$keyword};
114 }
115}
c3398f5b 116
117sub load_class {
118 my $class = shift;
262801ef 119
9694b71b 120 if (ref($class) || !defined($class) || !length($class)) {
121 my $display = defined($class) ? $class : 'undef';
122 confess "Invalid class name ($display)";
123 }
c3398f5b 124
6c169c50 125 return 1 if $class eq 'Mouse::Object';
2a674d23 126 return 1 if is_class_loaded($class);
127
c3398f5b 128 (my $file = "$class.pm") =~ s{::}{/}g;
129
130 eval { CORE::require($file) };
2a674d23 131 confess "Could not load class ($class) because : $@" if $@;
c3398f5b 132
133 return 1;
134}
135
2a674d23 136sub is_class_loaded {
137 my $class = shift;
138
7ecc2123 139 return 0 if ref($class) || !defined($class) || !length($class);
140
bf134049 141 # walk the symbol table tree to avoid autovififying
142 # \*{${main::}{"Foo::"}} == \*main::Foo::
143
144 my $pack = \*::;
145 foreach my $part (split('::', $class)) {
146 return 0 unless exists ${$$pack}{"${part}::"};
147 $pack = \*{${$$pack}{"${part}::"}};
2a674d23 148 }
bf134049 149
150 # check for $VERSION or @ISA
151 return 1 if exists ${$$pack}{VERSION}
152 && defined *{${$$pack}{VERSION}}{SCALAR};
153 return 1 if exists ${$$pack}{ISA}
154 && defined *{${$$pack}{ISA}}{ARRAY};
155
156 # check for any method
157 foreach ( keys %{$$pack} ) {
158 next if substr($_, -2, 2) eq '::';
159 return 1 if defined *{${$$pack}{$_}}{CODE};
160 }
161
162 # fail
2a674d23 163 return 0;
164}
165
c3398f5b 1661;
167
168__END__
169
170=head1 NAME
171
0fff36e6 172Mouse - Moose minus the antlers
c3398f5b 173
c3398f5b 174=head1 SYNOPSIS
175
176 package Point;
6caea456 177 use Mouse; # automatically turns on strict and warnings
178
179 has 'x' => (is => 'rw', isa => 'Int');
180 has 'y' => (is => 'rw', isa => 'Int');
181
182 sub clear {
183 my $self = shift;
184 $self->x(0);
185 $self->y(0);
186 }
187
188 package Point3D;
c3398f5b 189 use Mouse;
190
6caea456 191 extends 'Point';
c3398f5b 192
6caea456 193 has 'z' => (is => 'rw', isa => 'Int');
194
8517d2ff 195 after 'clear' => sub {
196 my $self = shift;
197 $self->z(0);
198 };
c3398f5b 199
200=head1 DESCRIPTION
201
0fff36e6 202L<Moose> is wonderful.
c3398f5b 203
0fff36e6 204Unfortunately, it's a little slow. Though significant progress has been made
205over the years, the compile time penalty is a non-starter for some
206applications.
207
208Mouse aims to alleviate this by providing a subset of Moose's
209functionality, faster. In particular, L<Moose/has> is missing only a few
210expert-level features.
211
d1c1b994 212We're also going as light on dependencies as possible. Most functions we use
213from L<Scalar::Util> are copied into this dist. L<Scalar::Util> is required if
214you'd like weak references; there's simply no way to do it from pure Perl.
215L<Class::Method::Modifiers> is required if you want support for L</before>,
216L</after>, and L</around>.
217
0fff36e6 218=head2 MOOSE COMPAT
219
220Compatibility with Moose has been the utmost concern. Fewer than 1% of the
221tests fail when run against Moose instead of Mouse. Mouse code coverage is also
7e3ed32e 222over 96%. Even the error messages are taken from Moose. The Mouse code just
223runs the test suite 4x faster.
0fff36e6 224
225The idea is that, if you need the extra power, you should be able to run
8e1a28a8 226C<s/Mouse/Moose/g> on your codebase and have nothing break. To that end,
227nothingmuch has written L<Squirrel> (part of this distribution) which will act
228as Mouse unless Moose is loaded, in which case it will act as Moose.
0fff36e6 229
230Mouse also has the blessings of Moose's author, stevan.
231
232=head2 MISSING FEATURES
233
0fff36e6 234=head3 Roles
235
faa5cb70 236We're working on fixing this one! stevan has suggested an implementation
237strategy. Mouse currently ignores methods, so that needs to be fixed next.
238Roles that consist entirely of attributes may be usable in this very version.
0fff36e6 239
240=head3 Complex types
241
242User-defined type constraints and parameterized types may be implemented. Type
243coercions probably not (patches welcome).
244
245=head3 Bootstrapped meta world
246
247Very handy for extensions to the MOP. Not pressing, but would be nice to have.
248
249=head3 Modification of attribute metaclass
250
251When you declare an attribute with L</has>, you get the inlined accessors
252installed immediately. Modifying the attribute metaclass, even if possible,
253does nothing.
254
255=head3 Lots more..
256
257MouseX?
258
259=head1 KEYWORDS
c3398f5b 260
306290e8 261=head2 meta -> Mouse::Meta::Class
c3398f5b 262
263Returns this class' metaclass instance.
264
265=head2 extends superclasses
266
267Sets this class' superclasses.
268
b7a74822 269=head2 before (method|methods) => Code
270
271Installs a "before" method modifier. See L<Moose/before> or
272L<Class::Method::Modifiers/before>.
273
6beb7db6 274Use of this feature requires L<Class::Method::Modifiers>!
275
b7a74822 276=head2 after (method|methods) => Code
277
278Installs an "after" method modifier. See L<Moose/after> or
279L<Class::Method::Modifiers/after>.
280
6beb7db6 281Use of this feature requires L<Class::Method::Modifiers>!
282
b7a74822 283=head2 around (method|methods) => Code
284
285Installs an "around" method modifier. See L<Moose/around> or
286L<Class::Method::Modifiers/around>.
287
6beb7db6 288Use of this feature requires L<Class::Method::Modifiers>!
289
c3398f5b 290=head2 has (name|names) => parameters
291
292Adds an attribute (or if passed an arrayref of names, multiple attributes) to
0fff36e6 293this class. Options:
294
295=over 4
296
297=item is => ro|rw
298
299If specified, inlines a read-only/read-write accessor with the same name as
300the attribute.
301
302=item isa => TypeConstraint
303
304Provides basic type checking in the constructor and accessor. Basic types such
305as C<Int>, C<ArrayRef>, C<Defined> are supported. Any unknown type is taken to
306be a class check (e.g. isa => 'DateTime' would accept only L<DateTime>
307objects).
308
309=item required => 0|1
310
311Whether this attribute is required to have a value. If the attribute is lazy or
312has a builder, then providing a value for the attribute in the constructor is
313optional.
314
ca63d17a 315=item init_arg => Str | Undef
0fff36e6 316
ca63d17a 317Allows you to use a different key name in the constructor. If undef, the
318attribue can't be passed to the constructor.
0fff36e6 319
320=item default => Value | CodeRef
321
322Sets the default value of the attribute. If the default is a coderef, it will
323be invoked to get the default value. Due to quirks of Perl, any bare reference
324is forbidden, you must wrap the reference in a coderef. Otherwise, all
325instances will share the same reference.
326
327=item lazy => 0|1
328
329If specified, the default is calculated on demand instead of in the
330constructor.
331
332=item predicate => Str
333
334Lets you specify a method name for installing a predicate method, which checks
335that the attribute has a value. It will not invoke a lazy default or builder
336method.
337
338=item clearer => Str
339
340Lets you specify a method name for installing a clearer method, which clears
341the attribute's value from the instance. On the next read, lazy or builder will
342be invoked.
343
344=item handles => HashRef|ArrayRef
345
346Lets you specify methods to delegate to the attribute. ArrayRef forwards the
347given method names to method calls on the attribute. HashRef maps local method
348names to remote method names called on the attribute. Other forms of
349L</handles>, such as regular expression and coderef, are not yet supported.
350
351=item weak_ref => 0|1
352
353Lets you automatically weaken any reference stored in the attribute.
354
6beb7db6 355Use of this feature requires L<Scalar::Util>!
356
844fa049 357=item trigger => CodeRef
358
359Any 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.
360
6beb7db6 361Mouse 0.05 supported more complex triggers, but this behavior is now removed.
0fff36e6 362
363=item builder => Str
364
365Defines a method name to be called to provide the default value of the
366attribute. C<< builder => 'build_foo' >> is mostly equivalent to
367C<< default => sub { $_[0]->build_foo } >>.
368
369=item auto_deref => 0|1
370
371Allows you to automatically dereference ArrayRef and HashRef attributes in list
372context. In scalar context, the reference is returned (NOT the list length or
373bucket status). You must specify an appropriate type constraint to use
374auto_deref.
375
5253d13d 376=item lazy_build => 0|1
377
378Automatically define lazy => 1 as well as builder => "_build_$attr", clearer =>
379"clear_$attr', predicate => 'has_$attr' unless they are already defined.
380
0fff36e6 381=back
c3398f5b 382
383=head2 confess error -> BOOM
384
385L<Carp/confess> for your convenience.
386
387=head2 blessed value -> ClassName | undef
388
389L<Scalar::Util/blessed> for your convenience.
390
391=head1 MISC
392
393=head2 import
394
6caea456 395Importing Mouse will default your class' superclass list to L<Mouse::Object>.
c3398f5b 396You may use L</extends> to replace the superclass list.
397
398=head2 unimport
399
0fff36e6 400Please unimport Mouse (C<no Mouse>) so that if someone calls one of the
401keywords (such as L</extends>) it will break loudly instead breaking subtly.
c3398f5b 402
403=head1 FUNCTIONS
404
405=head2 load_class Class::Name
406
6caea456 407This will load a given C<Class::Name> (or die if it's not loadable).
c3398f5b 408This function can be used in place of tricks like
409C<eval "use $module"> or using C<require>.
410
262801ef 411=head2 is_class_loaded Class::Name -> Bool
412
413Returns whether this class is actually loaded or not. It uses a heuristic which
414involves checking for the existence of C<$VERSION>, C<@ISA>, and any
415locally-defined method.
416
c817e8f1 417=head1 AUTHORS
c3398f5b 418
419Shawn M Moore, C<< <sartak at gmail.com> >>
420
fc9f8988 421Yuval Kogman, C<< <nothingmuch at woobling.org> >>
422
c817e8f1 423tokuhirom
424
425Yappo
426
0fff36e6 427with plenty of code borrowed from L<Class::MOP> and L<Moose>
428
c3398f5b 429=head1 BUGS
430
431No known bugs.
432
433Please report any bugs through RT: email
434C<bug-mouse at rt.cpan.org>, or browse
435L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Mouse>.
436
437=head1 COPYRIGHT AND LICENSE
438
439Copyright 2008 Shawn M Moore.
440
441This program is free software; you can redistribute it and/or modify it
442under the same terms as Perl itself.
443
444=cut
445