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
eab013b2 7our $VERSION = '0.08';
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
199=head2 MOOSE COMPAT
200
201Compatibility with Moose has been the utmost concern. Fewer than 1% of the
202tests fail when run against Moose instead of Mouse. Mouse code coverage is also
faa5cb70 203over 97%. Even the error messages are taken from Moose. The Mouse code just
8e1a28a8 204runs the test suite 3x-4x faster.
0fff36e6 205
206The idea is that, if you need the extra power, you should be able to run
8e1a28a8 207C<s/Mouse/Moose/g> on your codebase and have nothing break. To that end,
208nothingmuch has written L<Squirrel> (part of this distribution) which will act
209as Mouse unless Moose is loaded, in which case it will act as Moose.
0fff36e6 210
211Mouse also has the blessings of Moose's author, stevan.
212
213=head2 MISSING FEATURES
214
0fff36e6 215=head3 Roles
216
faa5cb70 217We're working on fixing this one! stevan has suggested an implementation
218strategy. Mouse currently ignores methods, so that needs to be fixed next.
219Roles that consist entirely of attributes may be usable in this very version.
0fff36e6 220
221=head3 Complex types
222
223User-defined type constraints and parameterized types may be implemented. Type
224coercions probably not (patches welcome).
225
226=head3 Bootstrapped meta world
227
228Very handy for extensions to the MOP. Not pressing, but would be nice to have.
229
230=head3 Modification of attribute metaclass
231
232When you declare an attribute with L</has>, you get the inlined accessors
233installed immediately. Modifying the attribute metaclass, even if possible,
234does nothing.
235
236=head3 Lots more..
237
238MouseX?
239
240=head1 KEYWORDS
c3398f5b 241
306290e8 242=head2 meta -> Mouse::Meta::Class
c3398f5b 243
244Returns this class' metaclass instance.
245
246=head2 extends superclasses
247
248Sets this class' superclasses.
249
b7a74822 250=head2 before (method|methods) => Code
251
252Installs a "before" method modifier. See L<Moose/before> or
253L<Class::Method::Modifiers/before>.
254
255=head2 after (method|methods) => Code
256
257Installs an "after" method modifier. See L<Moose/after> or
258L<Class::Method::Modifiers/after>.
259
260=head2 around (method|methods) => Code
261
262Installs an "around" method modifier. See L<Moose/around> or
263L<Class::Method::Modifiers/around>.
264
c3398f5b 265=head2 has (name|names) => parameters
266
267Adds an attribute (or if passed an arrayref of names, multiple attributes) to
0fff36e6 268this class. Options:
269
270=over 4
271
272=item is => ro|rw
273
274If specified, inlines a read-only/read-write accessor with the same name as
275the attribute.
276
277=item isa => TypeConstraint
278
279Provides basic type checking in the constructor and accessor. Basic types such
280as C<Int>, C<ArrayRef>, C<Defined> are supported. Any unknown type is taken to
281be a class check (e.g. isa => 'DateTime' would accept only L<DateTime>
282objects).
283
284=item required => 0|1
285
286Whether this attribute is required to have a value. If the attribute is lazy or
287has a builder, then providing a value for the attribute in the constructor is
288optional.
289
290=item init_arg => Str
291
292Allows you to use a different key name in the constructor.
293
294=item default => Value | CodeRef
295
296Sets the default value of the attribute. If the default is a coderef, it will
297be invoked to get the default value. Due to quirks of Perl, any bare reference
298is forbidden, you must wrap the reference in a coderef. Otherwise, all
299instances will share the same reference.
300
301=item lazy => 0|1
302
303If specified, the default is calculated on demand instead of in the
304constructor.
305
306=item predicate => Str
307
308Lets you specify a method name for installing a predicate method, which checks
309that the attribute has a value. It will not invoke a lazy default or builder
310method.
311
312=item clearer => Str
313
314Lets you specify a method name for installing a clearer method, which clears
315the attribute's value from the instance. On the next read, lazy or builder will
316be invoked.
317
318=item handles => HashRef|ArrayRef
319
320Lets you specify methods to delegate to the attribute. ArrayRef forwards the
321given method names to method calls on the attribute. HashRef maps local method
322names to remote method names called on the attribute. Other forms of
323L</handles>, such as regular expression and coderef, are not yet supported.
324
325=item weak_ref => 0|1
326
327Lets you automatically weaken any reference stored in the attribute.
328
844fa049 329=item trigger => CodeRef
330
331Any 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.
332
333Mouse 0.05 supported more complex triggers, but this behavior is now deprecated.
0fff36e6 334
335=item builder => Str
336
337Defines a method name to be called to provide the default value of the
338attribute. C<< builder => 'build_foo' >> is mostly equivalent to
339C<< default => sub { $_[0]->build_foo } >>.
340
341=item auto_deref => 0|1
342
343Allows you to automatically dereference ArrayRef and HashRef attributes in list
344context. In scalar context, the reference is returned (NOT the list length or
345bucket status). You must specify an appropriate type constraint to use
346auto_deref.
347
348=back
c3398f5b 349
350=head2 confess error -> BOOM
351
352L<Carp/confess> for your convenience.
353
354=head2 blessed value -> ClassName | undef
355
356L<Scalar::Util/blessed> for your convenience.
357
358=head1 MISC
359
360=head2 import
361
6caea456 362Importing Mouse will default your class' superclass list to L<Mouse::Object>.
c3398f5b 363You may use L</extends> to replace the superclass list.
364
365=head2 unimport
366
0fff36e6 367Please unimport Mouse (C<no Mouse>) so that if someone calls one of the
368keywords (such as L</extends>) it will break loudly instead breaking subtly.
c3398f5b 369
370=head1 FUNCTIONS
371
372=head2 load_class Class::Name
373
6caea456 374This will load a given C<Class::Name> (or die if it's not loadable).
c3398f5b 375This function can be used in place of tricks like
376C<eval "use $module"> or using C<require>.
377
262801ef 378=head2 is_class_loaded Class::Name -> Bool
379
380Returns whether this class is actually loaded or not. It uses a heuristic which
381involves checking for the existence of C<$VERSION>, C<@ISA>, and any
382locally-defined method.
383
c3398f5b 384=head1 AUTHOR
385
386Shawn M Moore, C<< <sartak at gmail.com> >>
387
0fff36e6 388with plenty of code borrowed from L<Class::MOP> and L<Moose>
389
c3398f5b 390=head1 BUGS
391
392No known bugs.
393
394Please report any bugs through RT: email
395C<bug-mouse at rt.cpan.org>, or browse
396L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Mouse>.
397
398=head1 COPYRIGHT AND LICENSE
399
400Copyright 2008 Shawn M Moore.
401
402This program is free software; you can redistribute it and/or modify it
403under the same terms as Perl itself.
404
405=cut
406