Using __PACKAGE__->meta->get_attribute('foo')
, you can access the foo
attribute definitions in a given class, which can be useful.
#!perl
package Bla;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 1;
no Moose; __PACKAGE__->meta->make_immutable;
package Blub;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 0;
no Moose; __PACKAGE__->meta->make_immutable;
package Blubbel;
use Moose;
extends 'Blub';
no Moose; __PACKAGE__->meta->make_immutable;
package main;
use Test::More;
use Test::Exception;
my $attr = Bla->meta->get_attribute('hui');
is $attr->is_required, 1;
$attr = Blub->meta->get_attribute('hui');
is $attr->is_required, 0;
$attr = Blubbel->meta->get_attribute('hui');
is $attr, undef;
throws_ok { $attr->is_required }
qr/Can't call method "is_required" on an undefined value/;
diag 'Attribute aus Basisklassen werden hier nicht gefunden.';
done_testing;
As evidenced by this little code sample, however, this cannot be used to access attribute definitions in base classes, which would be even more useful for my particular case. Is there a way to achieve what I want?
NOTE that
get_attribute
does not search superclasses, for that you need to usefind_attribute_by_name
— Class::MOP::Class docs. And indeed this code passes:
my $attr = Bla->meta->find_attribute_by_name('hui');
is $attr->is_required, 1;
$attr = Blub->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;
$attr = Blubbel->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With