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