skip temporary file for vim
[gitmo/Mouse.git] / lib / Mouse.pm
CommitLineData
eae80759 1
c3398f5b 2package Mouse;
3use strict;
4use warnings;
eae80759 5use 5.006;
eaad7dab 6use base 'Exporter';
c3398f5b 7
eae80759 8our $VERSION;
c3398f5b 9
eae80759 10BEGIN {
11 $VERSION = '0.12';
11ac534b 12
eae80759 13 if ($ENV{MOUSE_DEBUG}) {
14 *DEBUG = sub (){ 1 };
15 } else {
16 *DEBUG = sub (){ 0 };
17 }
11ac534b 18}
19
c3398f5b 20use Carp 'confess';
01db075b 21use Mouse::Util 'blessed';
c3398f5b 22
306290e8 23use Mouse::Meta::Attribute;
24use Mouse::Meta::Class;
c3398f5b 25use Mouse::Object;
d60c78b9 26use Mouse::TypeRegistry;
c3398f5b 27
eaad7dab 28our @EXPORT = qw(extends has before after around blessed confess with);
29
30sub extends { Mouse::Meta::Class->initialize(caller)->superclasses(@_) }
c3398f5b 31
eaad7dab 32sub has {
33 my $meta = Mouse::Meta::Class->initialize(caller);
c3398f5b 34
eaad7dab 35 my $names = shift;
36 $names = [$names] if !ref($names);
37
38 for my $name (@$names) {
39 if ($name =~ s/^\+//) {
40 Mouse::Meta::Attribute->clone_parent($meta, $name, @_);
41 }
42 else {
43 Mouse::Meta::Attribute->create($meta, $name, @_);
c3398f5b 44 }
45 }
eaad7dab 46}
47
48sub before {
49 my $meta = Mouse::Meta::Class->initialize(caller);
50
51 my $code = pop;
52
53 for (@_) {
54 $meta->add_before_method_modifier($_ => $code);
55 }
56}
57
58sub after {
59 my $meta = Mouse::Meta::Class->initialize(caller);
60
61 my $code = pop;
62
63 for (@_) {
64 $meta->add_after_method_modifier($_ => $code);
65 }
66}
67
68sub around {
69 my $meta = Mouse::Meta::Class->initialize(caller);
70
71 my $code = pop;
72
73 for (@_) {
74 $meta->add_around_method_modifier($_ => $code);
75 }
76}
77
78sub with {
21498b08 79 Mouse::Util::apply_all_roles((caller)[0], @_);
eaad7dab 80}
81
82sub import {
e15d73d2 83 my $class = shift;
84
eaad7dab 85 strict->import;
86 warnings->import;
87
88 my $caller = caller;
89
90 my $meta = Mouse::Meta::Class->initialize($caller);
91 $meta->superclasses('Mouse::Object')
92 unless $meta->superclasses;
93
94 no strict 'refs';
95 no warnings 'redefine';
96 *{$caller.'::meta'} = sub { $meta };
97
e15d73d2 98 if (@_) {
99 __PACKAGE__->export_to_level( 1, $class, @_);
100 } else {
101 # shortcut for the common case of no type character
102 no strict 'refs';
103 for my $keyword (@EXPORT) {
104 *{ $caller . '::' . $keyword } = *{__PACKAGE__ . '::' . $keyword};
105 }
106 }
eaad7dab 107}
108
109sub unimport {
110 my $caller = caller;
111
112 no strict 'refs';
113 for my $keyword (@EXPORT) {
114 delete ${ $caller . '::' }{$keyword};
115 }
116}
c3398f5b 117
118sub load_class {
119 my $class = shift;
262801ef 120
9694b71b 121 if (ref($class) || !defined($class) || !length($class)) {
122 my $display = defined($class) ? $class : 'undef';
123 confess "Invalid class name ($display)";
124 }
c3398f5b 125
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
c3398f5b 417=head1 AUTHOR
418
419Shawn M Moore, C<< <sartak at gmail.com> >>
420
fc9f8988 421Yuval Kogman, C<< <nothingmuch at woobling.org> >>
422
0fff36e6 423with plenty of code borrowed from L<Class::MOP> and L<Moose>
424
c3398f5b 425=head1 BUGS
426
427No known bugs.
428
429Please report any bugs through RT: email
430C<bug-mouse at rt.cpan.org>, or browse
431L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Mouse>.
432
433=head1 COPYRIGHT AND LICENSE
434
435Copyright 2008 Shawn M Moore.
436
437This program is free software; you can redistribute it and/or modify it
438under the same terms as Perl itself.
439
440=cut
441