From: Florian Ragwitz Date: Sat, 13 Dec 2008 13:12:12 +0000 (+0000) Subject: Allow attribute defaults to be objects with overloaded codification. X-Git-Tag: 0.73~6 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=3d4db6ecaa27ef648b9278368e8e85cfd61257f4;p=gitmo%2FClass-MOP.git Allow attribute defaults to be objects with overloaded codification. Tests by rhesa++. --- diff --git a/lib/Class/MOP/Attribute.pm b/lib/Class/MOP/Attribute.pm index 97b7d78..82d7bc7 100644 --- a/lib/Class/MOP/Attribute.pm +++ b/lib/Class/MOP/Attribute.pm @@ -241,7 +241,9 @@ sub get_write_method_ref { } sub is_default_a_coderef { - ('CODE' eq ref($_[0]->{'default'})) + my ($value) = $_[0]->{'default'}; + return unless ref($value); + return ref($value) eq 'CODE' || (blessed($value) && $value->can('(&{}')); } sub default { diff --git a/t/020_attribute.t b/t/020_attribute.t index 4dfbc2e..30bb9cd 100644 --- a/t/020_attribute.t +++ b/t/020_attribute.t @@ -5,7 +5,7 @@ use warnings; use Scalar::Util 'reftype', 'blessed'; -use Test::More tests => 100; +use Test::More tests => 104; use Test::Exception; use Class::MOP; @@ -227,3 +227,25 @@ dies_ok { Class::MOP::Attribute->name } q{... can't call name() as a class metho is($attr->builder, 'foo_builder', '... $attr->builder == foo_builder'); } + +{ + for my $value ({}, bless({}, 'Foo')) { + throws_ok { + Class::MOP::Attribute->new('$foo', default => $value); + } qr/References are not allowed as default values/; + } +} + +{ + { + package Method; + use overload '&{}' => sub { sub { $_[0] } }; + } + + my $attr; + lives_ok { + $attr = Class::MOP::Attribute->new('$foo', default => bless({}, 'Method')); + } 'objects with overloaded codification accepted as default'; + + is($attr->default(42), 42, 'default calculated correctly with overloaded object'); +}