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