X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FMouse%2FAttribute.pm;h=4c2caf0a9955b2eafdc5e0996338551ef76f184e;hb=a707f5877879f294bbaa3d0744ddd021c6a2ca9b;hp=325c24de4b361b6250e497e23ce4cde07fdb5fd1;hpb=7ee01d77a48acfaaf20e6c2488781344953dec78;p=gitmo%2FMouse.git diff --git a/lib/Mouse/Attribute.pm b/lib/Mouse/Attribute.pm index 325c24d..4c2caf0 100644 --- a/lib/Mouse/Attribute.pm +++ b/lib/Mouse/Attribute.pm @@ -16,35 +16,53 @@ sub new { bless \%args, $class; } -sub name { $_[0]->{name} } -sub class { $_[0]->{class} } -sub default { $_[0]->{default} } -sub predicate { $_[0]->{predicate} } -sub clearer { $_[0]->{clearer} } -sub handles { $_[0]->{handles} } -sub weak_ref { $_[0]->{weak_ref} } -sub init_arg { $_[0]->{init_arg} } +sub name { $_[0]->{name} } +sub class { $_[0]->{class} } +sub default { $_[0]->{default} } +sub predicate { $_[0]->{predicate} } +sub clearer { $_[0]->{clearer} } +sub handles { $_[0]->{handles} } +sub weak_ref { $_[0]->{weak_ref} } +sub init_arg { $_[0]->{init_arg} } +sub type_constraint { $_[0]->{type_constraint} } sub generate_accessor { my $attribute = shift; - my $key = $attribute->{init_arg}; - my $default = $attribute->{default}; - my $trigger = $attribute->{trigger}; + my $name = $attribute->{name}; + my $key = $attribute->{init_arg}; + my $default = $attribute->{default}; + my $trigger = $attribute->{trigger}; + my $type = $attribute->{type_constraint}; + + my $constraint = sub { + return unless $type; + + my $checker = Mouse::TypeRegistry->optimized_constraints->{$type}; + return $checker if $checker; + + confess "Unable to parse type constraint '$type'"; + }->(); my $accessor = 'sub { my $self = shift;'; if ($attribute->{is} eq 'rw') { $accessor .= 'if (@_) { - $self->{$key} = $_[0];'; + local $_ = $_[0];'; + + if ($constraint) { + $accessor .= 'Carp::confess("Attribute ($name) does not pass the type constraint because: Validation failed for \'$type\' failed with value $_") unless $constraint->();' + } + + $accessor .= '$self->{$key} = $_;'; if ($attribute->{weak_ref}) { $accessor .= 'Scalar::Util::weaken($self->{$key});'; } if ($trigger) { - $accessor .= '$trigger->($self, $_[0], $attribute);'; + $accessor .= '$trigger->($self, $_, $attribute);'; } $accessor .= '}'; @@ -125,6 +143,8 @@ sub create { if exists($args{handles}) && ref($args{handles}) ne 'HASH'; + $args{type_constraint} = delete $args{isa}; + my $attribute = $self->new(%args, name => $name, class => $class); my $meta = $class->meta;