2 package # hide the package from PAUSE
10 use base 'Class::MOP::Attribute';
12 # this is for an extra attribute constructor
13 # option, which is to be able to create a
14 # way for the class to access the history
15 AttributesWithHistory->meta->add_attribute('history_accessor' => (
16 reader => 'history_accessor',
17 init_arg => 'history_accessor',
18 predicate => 'has_history_accessor',
21 # this is a place to store the actual
22 # history of the attribute
23 AttributesWithHistory->meta->add_attribute('_history' => (
24 accessor => '_history',
25 default => sub { {} },
28 # generate the methods
30 sub generate_history_accessor_method {
31 my ($self, $attr_name) = @_;
33 unless (ref \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}) \{
34 \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\} = [];
36 \@\{\$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}\};
40 sub generate_accessor_method {
41 my ($self, $attr_name) = @_;
43 if (scalar(\@_) == 2) {
44 unless (ref \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}) \{
45 \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\} = [];
47 push \@\{\$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}\} => \$_[1];
48 \$_[0]->{'$attr_name'} = \$_[1];
50 \$_[0]->{'$attr_name'};
54 sub generate_writer_method {
55 my ($self, $attr_name) = @_;
57 unless (ref \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}) \{
58 \$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\} = [];
60 push \@\{\$_[0]->meta->get_attribute('$attr_name')->_history()->\{\$_[0]\}\} => \$_[1];
61 \$_[0]->{'$attr_name'} = \$_[1];
65 AttributesWithHistory->meta->add_after_method_modifier('install_accessors' => sub {
67 # and now add the history accessor
68 $self->associated_class->add_method(
69 $self->process_accessors('history_accessor' => $self->history_accessor())
70 ) if $self->has_history_accessor();
79 AttributesWithHistory - An example attribute metaclass which keeps a history of changes
85 Foo->meta->add_attribute(AttributesWithHistory->new('foo' => (
87 history_accessor => 'get_foo_history',
90 Foo->meta->add_attribute(AttributesWithHistory->new('bar' => (
93 history_accessor => 'get_bar_history',
98 $class->meta->new_object(@_);
103 This is an example of an attribute metaclass which keeps a
104 record of all the values it has been assigned. It stores the
105 history as a field in the attribute meta-object, and will
106 autogenerate a means of accessing that history for the class
107 which these attributes are added too.
111 Stevan Little E<lt>stevan@iinteractive.comE<gt>
113 Yuval Kogman E<lt>nothingmuch@woobling.comE<gt>
115 =head1 COPYRIGHT AND LICENSE
117 Copyright 2006 by Infinity Interactive, Inc.
119 L<http://www.iinteractive.com>
121 This library is free software; you can redistribute it and/or modify
122 it under the same terms as Perl itself.