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