对于通过构建器方法填充在消费类中的必需属性,可以在角色中使用after修饰符?
package A::Role;
use Moose::Role;
use IO::File;
use Carp;
requires 'properties_file';
after 'properties_file' => sub {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
};消费类:
package A::B::C;
use Moose;
use Carp;
use Moose;
use Carp;
use HA::Connection::SSH;
use constant {
...
};
has 'properties_file' => ( is => 'ro',
isa => 'Str',
builder => '_build_current_data');
with 'A::Role';
sub _build_current_data { ... }发布于 2013-02-19 01:03:57
回答你的问题:是的,你可以。您已经完成了关键部分,即在声明属性之后消费角色,以便生成访问器方法。
因此,您提供的代码将按照您期望的顺序执行:
my $c = A::B::C->new;
# 'properties_file' is built by _build_current_data()
my $filename = $c->properties_file;
# _check_prop_file() and _read_file() are executed (but before $filename is assigned)但是,通过获取properties_file来调用属性文件的检查和读取似乎确实很奇怪。如果您只想在构造后自动检查和读取属性文件,则角色可以提供一个BUILD方法,以便在类中使用。(BUILD是在构造之后执行的,所以properties_file已经初始化了。)
sub BUILD {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
return;
}https://stackoverflow.com/questions/14934101
复制相似问题