refactoring-n-tests
[gitmo/Class-MOP.git] / lib / Class / MOP / Attribute.pm
CommitLineData
8b978dd5 1
2package Class::MOP::Attribute;
3
4use strict;
5use warnings;
6
2eb717d5 7use Carp 'confess';
9ec169fe 8use Scalar::Util 'blessed', 'reftype', 'weaken';
2eb717d5 9
2bab2be6 10our $VERSION = '0.08';
8b978dd5 11
727919c5 12sub meta {
13 require Class::MOP::Class;
aa448b16 14 Class::MOP::Class->initialize(blessed($_[0]) || $_[0]);
727919c5 15}
2eb717d5 16
727919c5 17# NOTE: (meta-circularity)
18# This method will be replaces in the
19# boostrap section of Class::MOP, by
20# a new version which uses the
21# &Class::MOP::Class::construct_instance
22# method to build an attribute meta-object
23# which itself is described with attribute
24# meta-objects.
25# - Ain't meta-circularity grand? :)
8b978dd5 26sub new {
27 my $class = shift;
28 my $name = shift;
29 my %options = @_;
30
cbd9f942 31 (defined $name && $name)
8b978dd5 32 || confess "You must provide a name for the attribute";
5659d76e 33 $options{init_arg} = $name
34 if not exists $options{init_arg};
2eb717d5 35
8b978dd5 36 bless {
c50c603e 37 name => $name,
38 accessor => $options{accessor},
39 reader => $options{reader},
40 writer => $options{writer},
41 predicate => $options{predicate},
42 init_arg => $options{init_arg},
9ec169fe 43 default => $options{default},
44 # keep a weakened link to the
45 # class we are associated with
46 associated_class => undef,
8b978dd5 47 } => $class;
48}
49
7b31baf4 50# NOTE:
5659d76e 51# this is a primative (and kludgy) clone operation
52# for now, it will be repleace in the Class::MOP
53# bootstrap with a proper one, however we know
54# that this one will work fine for now.
55sub clone {
56 my $self = shift;
57 my %options = @_;
58 (blessed($self))
59 || confess "Can only clone an instance";
60 return bless { %{$self}, %options } => blessed($self);
61}
62
bd4e03f9 63sub initialize_instance_slot {
f892c0f0 64 my ($self, $meta_instance, $instance, $params) = @_;
291073fc 65 my $init_arg = $self->{init_arg};
bd4e03f9 66 # try to fetch the init arg from the %params ...
67 my $val;
68 $val = $params->{$init_arg} if exists $params->{$init_arg};
69 # if nothing was in the %params, we can use the
70 # attribute's default value (if it has one)
bb8dacfa 71 if (!defined $val && defined $self->{default}) {
2d711cc8 72 $val = $self->default($instance);
73 }
f892c0f0 74 $meta_instance->set_slot_value($instance, $self->name, $val);
bd4e03f9 75}
76
5659d76e 77# NOTE:
7b31baf4 78# the next bunch of methods will get bootstrapped
79# away in the Class::MOP bootstrapping section
80
c50c603e 81sub name { $_[0]->{name} }
82
7b31baf4 83sub associated_class { $_[0]->{associated_class} }
84
727919c5 85sub has_accessor { defined($_[0]->{accessor}) ? 1 : 0 }
86sub has_reader { defined($_[0]->{reader}) ? 1 : 0 }
87sub has_writer { defined($_[0]->{writer}) ? 1 : 0 }
c50c603e 88sub has_predicate { defined($_[0]->{predicate}) ? 1 : 0 }
727919c5 89sub has_init_arg { defined($_[0]->{init_arg}) ? 1 : 0 }
90sub has_default { defined($_[0]->{default}) ? 1 : 0 }
c50c603e 91
92sub accessor { $_[0]->{accessor} }
93sub reader { $_[0]->{reader} }
94sub writer { $_[0]->{writer} }
95sub predicate { $_[0]->{predicate} }
96sub init_arg { $_[0]->{init_arg} }
97
7b31baf4 98# end bootstrapped away method section.
99# (all methods below here are kept intact)
100
c50c603e 101sub default {
102 my $self = shift;
103 if (reftype($self->{default}) && reftype($self->{default}) eq 'CODE') {
727919c5 104 # if the default is a CODE ref, then
105 # we pass in the instance and default
106 # can return a value based on that
107 # instance. Somewhat crude, but works.
c50c603e 108 return $self->{default}->(shift);
109 }
110 $self->{default};
111}
8b978dd5 112
c57c8b10 113# slots
114
115sub slots { (shift)->name }
116
9ec169fe 117# class association
727919c5 118
9ec169fe 119sub attach_to_class {
120 my ($self, $class) = @_;
121 (blessed($class) && $class->isa('Class::MOP::Class'))
122 || confess "You must pass a Class::MOP::Class instance (or a subclass)";
123 weaken($self->{associated_class} = $class);
124}
125
126sub detach_from_class {
127 my $self = shift;
128 $self->{associated_class} = undef;
129}
130
131## Method generation helpers
132
133sub generate_accessor_method {
08388f17 134 my $self = shift;
2d711cc8 135 my $meta_instance = $self->associated_class->get_meta_instance;
49c93440 136 my $attr_name = $self->name;
137 return sub {
138 $meta_instance->set_slot_value($_[0], $attr_name, $_[1]) if scalar(@_) == 2;
139 $meta_instance->get_slot_value($_[0], $attr_name);
013b1897 140 };
9ec169fe 141}
142
143sub generate_reader_method {
08388f17 144 my $self = shift;
2d711cc8 145 my $meta_instance = $self->associated_class->get_meta_instance;
49c93440 146 my $attr_name = $self->name;
147 return sub {
b9dfbf78 148 confess "Cannot assign a value to a read-only accessor" if @_ > 1;
49c93440 149 $meta_instance->get_slot_value($_[0], $attr_name);
b9dfbf78 150 };
9ec169fe 151}
152
153sub generate_writer_method {
08388f17 154 my $self = shift;
2d711cc8 155 my $meta_instance = $self->associated_class->get_meta_instance;
49c93440 156 my $attr_name = $self->name;
157 return sub {
158 $meta_instance->set_slot_value($_[0], $attr_name, $_[1]);
2bab2be6 159 };
9ec169fe 160}
161
162sub generate_predicate_method {
08388f17 163 my $self = shift;
2d711cc8 164 my $meta_instance = $self->associated_class->get_meta_instance;
49c93440 165 my $attr_name = $self->name;
166 return sub {
167 defined $meta_instance->get_slot_value($_[0], $attr_name) ? 1 : 0;
2bab2be6 168 };
9ec169fe 169}
170
171sub process_accessors {
172 my ($self, $type, $accessor) = @_;
013b1897 173 if (reftype($accessor)) {
174 (reftype($accessor) eq 'HASH')
175 || confess "bad accessor/reader/writer/predicate format, must be a HASH ref";
9ec169fe 176 my ($name, $method) = each %{$accessor};
a4258ffd 177 return ($name, Class::MOP::Attribute::Accessor->wrap($method));
2eb717d5 178 }
9ec169fe 179 else {
180 my $generator = $self->can('generate_' . $type . '_method');
181 ($generator)
182 || confess "There is no method generator for the type='$type'";
183 if (my $method = $self->$generator($self->name)) {
a4258ffd 184 return ($accessor => Class::MOP::Attribute::Accessor->wrap($method));
9ec169fe 185 }
343203ee 186 confess "Could not create the '$type' method for " . $self->name . " because : $@";
9ec169fe 187 }
188}
189
190sub install_accessors {
191 my $self = shift;
192 my $class = $self->associated_class;
c50c603e 193
9ec169fe 194 $class->add_method(
195 $self->process_accessors('accessor' => $self->accessor())
196 ) if $self->has_accessor();
197
198 $class->add_method(
199 $self->process_accessors('reader' => $self->reader())
200 ) if $self->has_reader();
201
202 $class->add_method(
203 $self->process_accessors('writer' => $self->writer())
204 ) if $self->has_writer();
205
206 $class->add_method(
207 $self->process_accessors('predicate' => $self->predicate())
208 ) if $self->has_predicate();
209 return;
2eb717d5 210}
211
b51af7f9 212{
213 my $_remove_accessor = sub {
214 my ($accessor, $class) = @_;
c50c603e 215 if (reftype($accessor) && reftype($accessor) eq 'HASH') {
216 ($accessor) = keys %{$accessor};
217 }
b51af7f9 218 my $method = $class->get_method($accessor);
219 $class->remove_method($accessor)
2eb717d5 220 if (blessed($method) && $method->isa('Class::MOP::Attribute::Accessor'));
b51af7f9 221 };
c50c603e 222
b51af7f9 223 sub remove_accessors {
9ec169fe 224 my $self = shift;
225 $_remove_accessor->($self->accessor(), $self->associated_class()) if $self->has_accessor();
226 $_remove_accessor->($self->reader(), $self->associated_class()) if $self->has_reader();
227 $_remove_accessor->($self->writer(), $self->associated_class()) if $self->has_writer();
228 $_remove_accessor->($self->predicate(), $self->associated_class()) if $self->has_predicate();
b51af7f9 229 return;
230 }
231
8b978dd5 232}
233
2eb717d5 234package Class::MOP::Attribute::Accessor;
235
236use strict;
237use warnings;
238
727919c5 239use Class::MOP::Method;
240
2eb717d5 241our $VERSION = '0.01';
242
243our @ISA = ('Class::MOP::Method');
244
8b978dd5 2451;
246
247__END__
248
249=pod
250
251=head1 NAME
252
253Class::MOP::Attribute - Attribute Meta Object
254
255=head1 SYNOPSIS
256
257 Class::MOP::Attribute->new('$foo' => (
fe122940 258 accessor => 'foo', # dual purpose get/set accessor
259 predicate => 'has_foo' # predicate check for defined-ness
260 init_arg => '-foo', # class->new will look for a -foo key
261 default => 'BAR IS BAZ!' # if no -foo key is provided, use this
8b978dd5 262 ));
263
264 Class::MOP::Attribute->new('$.bar' => (
fe122940 265 reader => 'bar', # getter
266 writer => 'set_bar', # setter
267 predicate => 'has_bar' # predicate check for defined-ness
268 init_arg => ':bar', # class->new will look for a :bar key
8b978dd5 269 # no default value means it is undef
270 ));
271
272=head1 DESCRIPTION
273
fe122940 274The Attribute Protocol is almost entirely an invention of this module,
275and is completely optional to this MOP. This is because Perl 5 does not
276have consistent notion of what is an attribute of a class. There are
277so many ways in which this is done, and very few (if any) are
278easily discoverable by this module.
552e3d24 279
280So, all that said, this module attempts to inject some order into this
fe122940 281chaos, by introducing a consistent API which can be used to create
282object attributes.
552e3d24 283
284=head1 METHODS
285
286=head2 Creation
287
288=over 4
289
fe122940 290=item B<new ($name, ?%options)>
291
292An attribute must (at the very least), have a C<$name>. All other
a2e85e6c 293C<%options> are contained added as key-value pairs. Acceptable keys
fe122940 294are as follows:
295
296=over 4
297
298=item I<init_arg>
299
300This should be a string value representing the expected key in
301an initialization hash. For instance, if we have an I<init_arg>
302value of C<-foo>, then the following code will Just Work.
303
304 MyClass->meta->construct_instance(-foo => "Hello There");
305
7b31baf4 306In an init_arg is not assigned, it will automatically use the
307value of C<$name>.
308
fe122940 309=item I<default>
310
311The value of this key is the default value which
312C<Class::MOP::Class::construct_instance> will initialize the
313attribute to.
314
315B<NOTE:>
316If the value is a simple scalar (string or number), then it can
317be just passed as is. However, if you wish to initialize it with
318a HASH or ARRAY ref, then you need to wrap that inside a CODE
319reference, like so:
320
321 Class::MOP::Attribute->new('@foo' => (
322 default => sub { [] },
323 ));
324
325 # or ...
326
327 Class::MOP::Attribute->new('%foo' => (
328 default => sub { {} },
329 ));
330
331If you wish to initialize an attribute with a CODE reference
332itself, then you need to wrap that in a subroutine as well, like
333so:
334
335 Class::MOP::Attribute->new('&foo' => (
336 default => sub { sub { print "Hello World" } },
337 ));
338
339And lastly, if the value of your attribute is dependent upon
340some other aspect of the instance structure, then you can take
341advantage of the fact that when the I<default> value is a CODE
342reference, it is passed the raw (unblessed) instance structure
343as it's only argument. So you can do things like this:
344
345 Class::MOP::Attribute->new('$object_identity' => (
346 default => sub { Scalar::Util::refaddr($_[0]) },
347 ));
348
349This last feature is fairly limited as there is no gurantee of
350the order of attribute initializations, so you cannot perform
351any kind of dependent initializations. However, if this is
352something you need, you could subclass B<Class::MOP::Class> and
353this class to acheive it. However, this is currently left as
354an exercise to the reader :).
355
356=back
357
a2e85e6c 358The I<accessor>, I<reader>, I<writer> and I<predicate> keys can
fe122940 359contain either; the name of the method and an appropriate default
360one will be generated for you, B<or> a HASH ref containing exactly one
361key (which will be used as the name of the method) and one value,
362which should contain a CODE reference which will be installed as
363the method itself.
59e7697f 364
365=over 4
366
367=item I<accessor>
368
fe122940 369The I<accessor> is a standard perl-style read/write accessor. It will
370return the value of the attribute, and if a value is passed as an argument,
371it will assign that value to the attribute.
372
373B<NOTE:>
374This method will properly handle the following code, by assigning an
375C<undef> value to the attribute.
376
377 $object->set_something(undef);
378
59e7697f 379=item I<reader>
380
fe122940 381This is a basic read-only accessor, it will just return the value of
382the attribute.
383
59e7697f 384=item I<writer>
385
fe122940 386This is a basic write accessor, it accepts a single argument, and
387assigns that value to the attribute. This method does not intentially
388return a value, however perl will return the result of the last
389expression in the subroutine, which returns in this returning the
390same value that it was passed.
59e7697f 391
fe122940 392B<NOTE:>
393This method will properly handle the following code, by assigning an
394C<undef> value to the attribute.
59e7697f 395
fe122940 396 $object->set_something();
397
398=item I<predicate>
399
400This is a basic test to see if the value of the attribute is not
401C<undef>. It will return true (C<1>) if the attribute's value is
402defined, and false (C<0>) otherwise.
59e7697f 403
404=back
552e3d24 405
bd4e03f9 406=item B<clone (%options)>
407
408=item B<initialize_instance_slot ($instance, $params)>
409
552e3d24 410=back
411
412=head2 Informational
413
fe122940 414These are all basic read-only value accessors for the values
415passed into C<new>. I think they are pretty much self-explanitory.
416
552e3d24 417=over 4
418
419=item B<name>
420
421=item B<accessor>
422
423=item B<reader>
424
425=item B<writer>
426
c50c603e 427=item B<predicate>
428
552e3d24 429=item B<init_arg>
430
fe122940 431=item B<default (?$instance)>
432
433As noted in the documentation for C<new> above, if the I<default>
434value is a CODE reference, this accessor will pass a single additional
435argument C<$instance> into it and return the value.
552e3d24 436
c57c8b10 437=item B<slots>
438
439Returns a list of slots required by the attribute. This is usually
440just one, which is the name of the attribute.
441
552e3d24 442=back
443
444=head2 Informational predicates
445
a2e85e6c 446These are all basic predicate methods for the values passed into C<new>.
fe122940 447
552e3d24 448=over 4
449
450=item B<has_accessor>
451
552e3d24 452=item B<has_reader>
453
552e3d24 454=item B<has_writer>
455
c50c603e 456=item B<has_predicate>
457
552e3d24 458=item B<has_init_arg>
459
552e3d24 460=item B<has_default>
461
552e3d24 462=back
463
9ec169fe 464=head2 Class association
465
466=over 4
467
468=item B<associated_class>
469
470=item B<attach_to_class ($class)>
471
472=item B<detach_from_class>
473
2d711cc8 474=item B<slot_name>
475
476=item B<allocate_slots>
477
478=item B<deallocate_slots>
479
9ec169fe 480=back
481
552e3d24 482=head2 Attribute Accessor generation
483
484=over 4
485
9ec169fe 486=item B<install_accessors>
2eb717d5 487
488This allows the attribute to generate and install code for it's own
a2e85e6c 489I<accessor/reader/writer/predicate> methods. This is called by
fe122940 490C<Class::MOP::Class::add_attribute>.
2eb717d5 491
9ec169fe 492This method will call C<process_accessors> for each of the possible
493method types (accessor, reader, writer & predicate).
494
495=item B<process_accessors ($type, $value)>
496
497This takes a C<$type> (accessor, reader, writer or predicate), and
498a C<$value> (the value passed into the constructor for each of the
499different types). It will then either generate the method itself
500(using the C<generate_*_method> methods listed below) or it will
501use the custom method passed through the constructor.
502
503=over 4
504
08388f17 505=item B<generate_accessor_method>
9ec169fe 506
08388f17 507=item B<generate_predicate_method>
9ec169fe 508
08388f17 509=item B<generate_reader_method>
9ec169fe 510
08388f17 511=item B<generate_writer_method>
9ec169fe 512
513=back
514
515=item B<remove_accessors>
2eb717d5 516
517This allows the attribute to remove the method for it's own
a2e85e6c 518I<accessor/reader/writer/predicate>. This is called by
fe122940 519C<Class::MOP::Class::remove_attribute>.
2eb717d5 520
521=back
522
523=head2 Introspection
524
525=over 4
552e3d24 526
2eb717d5 527=item B<meta>
552e3d24 528
fe122940 529This will return a B<Class::MOP::Class> instance which is related
530to this class.
531
532It should also be noted that B<Class::MOP> will actually bootstrap
533this module by installing a number of attribute meta-objects into
534it's metaclass. This will allow this class to reap all the benifits
535of the MOP when subclassing it.
536
552e3d24 537=back
538
8b978dd5 539=head1 AUTHOR
540
a2e85e6c 541Stevan Little E<lt>stevan@iinteractive.comE<gt>
8b978dd5 542
543=head1 COPYRIGHT AND LICENSE
544
545Copyright 2006 by Infinity Interactive, Inc.
546
547L<http://www.iinteractive.com>
548
549This library is free software; you can redistribute it and/or modify
550it under the same terms as Perl itself.
551
9ec169fe 552=cut