Moose (Perl): доступ к определениям атрибутов в базовых классах - PullRequest
7 голосов
/ 03 июня 2011

Используя __PACKAGE__->meta->get_attribute('foo'), вы можете получить доступ к определениям атрибутов foo в данном классе, что может быть полезно.

#!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;

Однако, как свидетельствует этот небольшой пример кода, его нельзя использовать для доступа к определениям атрибутов в базовых классах, что было бы еще более полезно для моего конкретного случая. Есть ли способ добиться того, чего я хочу?

1 Ответ

9 голосов
/ 03 июня 2011

Обратите внимание, что get_attribute не ищет суперклассы, для этого вам нужно использовать find_attribute_by_name

- Класс :: MOP :: Класс документов . И действительно, этот код проходит:

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;
...