1

我不能用MooseX::Declare.

use MooseX::Declare;

role Person {
has 'name' => (
    is => 'ro',
    isa => 'Str',
    default => 'John',
    );
}

class Me with Person {
has '+name' => (
        default => 'Michael',
    );
}

执行代码报错:

Could not find an attribute by the name of 'name' to inherit from in Me at /usr/lib/perl5/Moose/Meta/Class.pm line 711
Moose::Meta::Class::_process_inherited_attribute('Moose::Meta::Class=HASH(0x2b20628)', 'name', 'default', 'Michael', 'definition_context', 'HASH(0x114fd38)') called at /usr/lib/perl5/Moose/Meta/Class.pm line 694
Moose::Meta::Class::_process_attribute('Moose::Meta::Class=HASH(0x2b20628)', '+name', 'default', 'Michael', 'definition_context', 'HASH(0x114fd38)') called at /usr/lib/perl5/Moose/Meta/Class.pm line 566
Moose::Meta::Class::add_attribute('Moose::Meta::Class=HASH(0x2b20628)', '+name', 'default', 'Michael', 'definition_context', 'HASH(0x114fd38)') called at /usr/lib/perl5/Moose.pm line 79
Moose::has('Moose::Meta::Class=HASH(0x2b20628)', '+name', 'default', 'Michael') called at /usr/lib/perl5/Moose/Exporter.pm line 370
Moose::has('+name', 'default', 'Michael') called at Test.pm line 12
main::__ANON__() called at /usr/share/perl5/MooseX/Declare/Syntax/MooseSetup.pm line 81
MooseX::Declare::Syntax::MooseSetup::__ANON__('CODE(0x2b0be20)') called at Test.pm line 21

这有效,但它不是基于角色:

class Person {
has 'name' => (
    is => 'ro',
    isa => 'Str',
    default => 'John',
    );
}

class Me extends Person {
has '+name' => (
    default => 'Michael',
    );
}

使用角色时我的代码有什么问题?有没有可能覆盖属性行为?

4

1 回答 1

3

irc.perl.org #moose 的 irc 用户给出了解决方案:

<phaylon> iirc MX:Declare will consume the roles declared in the block at the end. try with 'Person'; in the class block before the has 

所以下面的代码现在可以工作了:

use MooseX::Declare;

role Person {
  has 'name' => (
    is => 'ro',
    isa => 'Str',
    default => 'John',
  );
}

class Me {
  with 'Person';

  has '+name' => (
    default => 'Michael',
  );
}

非常感谢phaylon

于 2013-03-28T12:14:19.433 回答