From: Stevan Little Date: Fri, 21 Apr 2006 14:49:15 +0000 (+0000) Subject: find_attribute_by_name X-Git-Tag: 0_26~7 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=058c1cf58078cdd0fcb9aa2f4a5c7556e0b8c23a;p=gitmo%2FClass-MOP.git find_attribute_by_name --- diff --git a/lib/Class/MOP/Class.pm b/lib/Class/MOP/Class.pm index 91fcf3b..fc3626e 100644 --- a/lib/Class/MOP/Class.pm +++ b/lib/Class/MOP/Class.pm @@ -532,6 +532,24 @@ sub compute_all_applicable_attributes { return @attrs; } +sub find_attribute_by_name { + my ($self, $attr_name) = @_; + # keep a record of what we have seen + # here, this will handle all the + # inheritence issues because we are + # using the &class_precedence_list + my %seen_class; + foreach my $class ($self->class_precedence_list()) { + next if $seen_class{$class}; + $seen_class{$class}++; + # fetch the meta-class ... + my $meta = $self->initialize($class); + return $meta->get_attribute($attr_name) + if $meta->has_attribute($attr_name); + } + return; +} + # Class attributes sub add_package_variable { @@ -1110,6 +1128,12 @@ HASH reference like C because all that same information is discoverable through the attribute meta-object itself. +=item B + +This method will traverse the inheritance heirachy and find the +first attribute whose name matches C<$attr_name>, then return it. +It will return undef if nothing is found. + =back =head2 Package Variables diff --git a/t/005_attributes.t b/t/005_attributes.t index d1ac414..63158f1 100644 --- a/t/005_attributes.t +++ b/t/005_attributes.t @@ -3,7 +3,7 @@ use strict; use warnings; -use Test::More tests => 40; +use Test::More tests => 43; use Test::Exception; BEGIN { @@ -78,6 +78,10 @@ my $BAR_ATTR_2 = Class::MOP::Attribute->new('$bar'); my $meta = Baz->meta; isa_ok($meta, 'Class::MOP::Class'); + is($meta->find_attribute_by_name('$bar'), $BAR_ATTR, '... got the right attribute for "bar"'); + is($meta->find_attribute_by_name('$baz'), $BAZ_ATTR, '... got the right attribute for "baz"'); + is($meta->find_attribute_by_name('$foo'), $FOO_ATTR, '... got the right attribute for "foo"'); + is_deeply( [ sort { $a->name cmp $b->name } $meta->compute_all_applicable_attributes() ], [ diff --git a/t/010_self_introspection.t b/t/010_self_introspection.t index 1bd53cf..a59ef86 100644 --- a/t/010_self_introspection.t +++ b/t/010_self_introspection.t @@ -3,7 +3,7 @@ use strict; use warnings; -use Test::More tests => 134; +use Test::More tests => 136; use Test::Exception; BEGIN { @@ -43,7 +43,7 @@ my @methods = qw( add_before_method_modifier add_after_method_modifier add_around_method_modifier has_attribute get_attribute add_attribute remove_attribute - get_attribute_list get_attribute_map compute_all_applicable_attributes + get_attribute_list get_attribute_map compute_all_applicable_attributes find_attribute_by_name add_package_variable get_package_variable has_package_variable remove_package_variable );