X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=examples%2FLazyClass.pod;h=184793986b4c1551524b7c33b893ec8fc824bf6b;hb=839ea97307cde7e936bff72d3f76d6213b9883a9;hp=cb678b14e49b8a1bd884058fa195dbdc396a5d10;hpb=c9e77dbb017258dc44295fc4ec8e0bdd99ec9361;p=gitmo%2FClass-MOP.git diff --git a/examples/LazyClass.pod b/examples/LazyClass.pod index cb678b1..1847939 100644 --- a/examples/LazyClass.pod +++ b/examples/LazyClass.pod @@ -1,40 +1,29 @@ package # hide the package from PAUSE - LazyClass; + LazyClass::Attribute; use strict; use warnings; -our $VERSION = '0.02'; - -use base 'Class::MOP::Class'; - -sub construct_instance { - my ($class, %params) = @_; - my $instance = {}; - foreach my $attr ($class->compute_all_applicable_attributes()) { - # if the attr has an init_arg, use that, otherwise, - # use the attributes name itself as the init_arg - my $init_arg = $attr->has_init_arg() ? $attr->init_arg() : $attr->name; - # try to fetch the init arg from the %params ... - my $val; - $val = $params{$init_arg} if exists $params{$init_arg}; - # now add this to the instance structure - # only if we have found a value at all - $instance->{$attr->name} = $val if defined $val; - } - return $instance; -} +use Carp 'confess'; -package # hide the package from PAUSE - LazyClass::Attribute; +our $VERSION = '0.03'; -use strict; -use warnings; +use base 'Class::MOP::Attribute'; -our $VERSION = '0.02'; +sub initialize_instance_slot { + my ($self, $class, $meta_instance, $params) = @_; + # if the attr has an init_arg, use that, otherwise, + # use the attributes name itself as the init_arg + my $init_arg = $self->init_arg(); + # try to fetch the init arg from the %params ... + my $val; + $val = $params->{$init_arg} if exists $params->{$init_arg}; + # now add this to the instance structure + # only if we have found a value at all + $meta_instance->add_slot($self->name, $val) if defined $val; +} -use base 'Class::MOP::Attribute'; sub generate_accessor_method { my ($self, $attr_name) = @_; @@ -55,6 +44,7 @@ sub generate_accessor_method { sub generate_reader_method { my ($self, $attr_name) = @_; sub { + confess "Cannot assign a value to a read-only accessor" if @_ > 1; if (!exists $_[0]->{$attr_name}) { my $attr = $self->associated_class->get_attribute($attr_name); $_[0]->{$attr_name} = $attr->has_default ? $attr->default($_[0]) : undef; @@ -77,7 +67,7 @@ LazyClass - An example metaclass with lazy initialization package BinaryTree; - use metaclass 'LazyClass' => ( + use metaclass 'Class::MOP::Class' => ( ':attribute_metaclass' => 'LazyClass::Attribute' ); @@ -96,9 +86,9 @@ LazyClass - An example metaclass with lazy initialization default => sub { BinaryTree->new() } )); - sub new { + sub new { my $class = shift; - bless $class->meta->construct_instance(@_) => $class; + $class->meta->new_object(@_); } # ... later in code