Moo处理=> '作用'不工作

时间:2014-12-12 22:03:25

标签: perl moo

对于我的生活,我无法弄清楚为什么这不符合文档所说的方式。我已经搜索了搜索到的问题,查看了源代码等等。这是一个错误还是我做错了,我看不到。

这是代码:     #!/ usr / bin / env perl

use strict;
use warnings;

package Model;

use Moo::Role;

has ObjectID => (
    is => 'rw'
);

package Object;

use Moo; 
use namespace::clean;

has model => (
    is => 'rw',
    handles => 'Model'
);

package main;

my $xo = Object->new;
$xo->ObjectID(12345);

exit;

尝试运行

perl -MCarp::Always t/moohandles.t

得到这个

Attempted to access 'model' but it is not set at (eval 26) line 20.
    Object::_assert_model('Object=HASH(0x1dfd118)') called at (eval 25) line 17
    Object::ObjectID('Object=HASH(0x1dfd118)', 12345) called at t/moohandles.t line 27

1 个答案:

答案 0 :(得分:4)

委派基本上将$xo->ObjectID方法调用扩展为$xo->model->ObjectID。但是$xo->model目前尚未设置。您可能希望将其默认为使用Model角色的对象。

这样的事情:

use strict;
use warnings;

{
  package Model;
  use Moo::Role;
  has ObjectID => (
    is => 'rw',
  );
}

{
  package ModelClass;
  use Moo;
  with 'Model';
}

{
  package Object;
  use Moo;
  has model => (
    is => 'rw',
    handles => 'Model',
    builder => sub { ModelClass->new },
  );
}

my $xo = Object->new;
$xo->ObjectID(12345);
print $xo->ObjectID, "\n";