Note our deplessness
[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
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
261=head2 after (method|methods) => Code
262
263Installs an "after" method modifier. See L<Moose/after> or
264L<Class::Method::Modifiers/after>.
265
266=head2 around (method|methods) => Code
267
268Installs an "around" method modifier. See L<Moose/around> or
269L<Class::Method::Modifiers/around>.
270
c3398f5b 271=head2 has (name|names) => parameters
272
273Adds an attribute (or if passed an arrayref of names, multiple attributes) to
0fff36e6 274this class. Options:
275
276=over 4
277
278=item is => ro|rw
279
280If specified, inlines a read-only/read-write accessor with the same name as
281the attribute.
282
283=item isa => TypeConstraint
284
285Provides basic type checking in the constructor and accessor. Basic types such
286as C<Int>, C<ArrayRef>, C<Defined> are supported. Any unknown type is taken to
287be a class check (e.g. isa => 'DateTime' would accept only L<DateTime>
288objects).
289
290=item required => 0|1
291
292Whether this attribute is required to have a value. If the attribute is lazy or
293has a builder, then providing a value for the attribute in the constructor is
294optional.
295
296=item init_arg => Str
297
298Allows you to use a different key name in the constructor.
299
300=item default => Value | CodeRef
301
302Sets the default value of the attribute. If the default is a coderef, it will
303be invoked to get the default value. Due to quirks of Perl, any bare reference
304is forbidden, you must wrap the reference in a coderef. Otherwise, all
305instances will share the same reference.
306
307=item lazy => 0|1
308
309If specified, the default is calculated on demand instead of in the
310constructor.
311
312=item predicate => Str
313
314Lets you specify a method name for installing a predicate method, which checks
315that the attribute has a value. It will not invoke a lazy default or builder
316method.
317
318=item clearer => Str
319
320Lets you specify a method name for installing a clearer method, which clears
321the attribute's value from the instance. On the next read, lazy or builder will
322be invoked.
323
324=item handles => HashRef|ArrayRef
325
326Lets you specify methods to delegate to the attribute. ArrayRef forwards the
327given method names to method calls on the attribute. HashRef maps local method
328names to remote method names called on the attribute. Other forms of
329L</handles>, such as regular expression and coderef, are not yet supported.
330
331=item weak_ref => 0|1
332
333Lets you automatically weaken any reference stored in the attribute.
334
844fa049 335=item trigger => CodeRef
336
337Any 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.
338
339Mouse 0.05 supported more complex triggers, but this behavior is now deprecated.
0fff36e6 340
341=item builder => Str
342
343Defines a method name to be called to provide the default value of the
344attribute. C<< builder => 'build_foo' >> is mostly equivalent to
345C<< default => sub { $_[0]->build_foo } >>.
346
347=item auto_deref => 0|1
348
349Allows you to automatically dereference ArrayRef and HashRef attributes in list
350context. In scalar context, the reference is returned (NOT the list length or
351bucket status). You must specify an appropriate type constraint to use
352auto_deref.
353
354=back
c3398f5b 355
356=head2 confess error -> BOOM
357
358L<Carp/confess> for your convenience.
359
360=head2 blessed value -> ClassName | undef
361
362L<Scalar::Util/blessed> for your convenience.
363
364=head1 MISC
365
366=head2 import
367
6caea456 368Importing Mouse will default your class' superclass list to L<Mouse::Object>.
c3398f5b 369You may use L</extends> to replace the superclass list.
370
371=head2 unimport
372
0fff36e6 373Please unimport Mouse (C<no Mouse>) so that if someone calls one of the
374keywords (such as L</extends>) it will break loudly instead breaking subtly.
c3398f5b 375
376=head1 FUNCTIONS
377
378=head2 load_class Class::Name
379
6caea456 380This will load a given C<Class::Name> (or die if it's not loadable).
c3398f5b 381This function can be used in place of tricks like
382C<eval "use $module"> or using C<require>.
383
262801ef 384=head2 is_class_loaded Class::Name -> Bool
385
386Returns whether this class is actually loaded or not. It uses a heuristic which
387involves checking for the existence of C<$VERSION>, C<@ISA>, and any
388locally-defined method.
389
c3398f5b 390=head1 AUTHOR
391
392Shawn M Moore, C<< <sartak at gmail.com> >>
393
0fff36e6 394with plenty of code borrowed from L<Class::MOP> and L<Moose>
395
c3398f5b 396=head1 BUGS
397
398No known bugs.
399
400Please report any bugs through RT: email
401C<bug-mouse at rt.cpan.org>, or browse
402L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Mouse>.
403
404=head1 COPYRIGHT AND LICENSE
405
406Copyright 2008 Shawn M Moore.
407
408This program is free software; you can redistribute it and/or modify it
409under the same terms as Perl itself.
410
411=cut
412