【问题标题】:Moose (Perl): access attribute definitions in base classesMoose (Perl):访问基类中的属性定义
【发布时间】:2011-09-07 22:47:33
【问题描述】:

使用__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;

然而,正如这个小代码示例所证明的那样,这不能用于访问基类中的属性定义,这对于我的特定情况会更加有用。有没有办法实现我想要的?

【问题讨论】:

    标签: perl moose


    【解决方案1】:

    注意get_attribute 不搜索超类,为此您需要使用find_attribute_by_name

    ——Class::MOP::Class docs。确实,这段代码通过了:

    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;
    

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      相关资源
      最近更新 更多