【发布时间】:2013-11-20 21:43:27
【问题描述】:
需要制作一个接受一个或多个paths的模块,并将它们强制转换为Class::Path 的数组。在 CPAN 中存在一个模块 MooseX::Types::Path::Class。从它的来源我发现模块定义的子类型Dir 和File。
我的示例模块:
package Web::Finder;
use namespace::sweep;
use Modern::Perl;
use Moose;
use MooseX::Types::Path::Class qw(Dir); #??? - is this correct?
use Method::Signatures::Simple;
use Path::Class;
#should accept one or more directories as Str or as Path::Class::Dir
has 'volumes' => (
is => 'ro',
isa => 'ArrayRef[Path::Class::Dir]', #Can I use here a simple 'ArrayRef[Dir]' ?
required => 1,
coerce => 1,
);
has 'fs' => (
is => 'ro',
isa => 'ArrayRef[File::System]',
lazy => 1,
builder => '_create_volumes',
);
#is the next correct?
method _create_volumes {
push $self->fs, File::System->new('Real', root => $_->stringify) for ($self->volumes);
}
还有我的剧本
#!/usr/bin/env perl
use Modern::Perl;
use Web::Finder;
my $f = Web::Finder->new(volumes => .... ???
我应该在上面的模块中改变什么来接受下一次初始化?
my $f = My::Module->new(volumes => "/some/path");
和
my $f = My::Module->new(volumes => [qw(/some/path1 /another/path2)] );
或类似的东西 - 所以:一条或多条路径...
根据我理解的错误消息,我比我做错了什么... ;)
You cannot coerce an attribute (volumes) unless its type (ArrayRef[Path::Class::Dir]) has a coercion at Web/Finder.pm line 14.
require Web/Finder.pm called at x line 2
main::BEGIN() called at Web/Finder.pm line 0
eval {...} called at Web/Finder.pm line 0
Attribute (volumes) does not pass the type constraint because: Validation failed for 'ArrayRef[Path::Class::Dir]' with value ARRAY(0x7f812b0040b8) at constructor Web::Finder::new (defined at Web/Finder.pm line 33) line 42.
Web::Finder::new("Web::Finder", "volumes", ARRAY(0x7f812b0040b8)) called at x line 6
问题的下一部分是如何为每个volume 创建一个File::System 实例。 builder 方法正确吗?
会很高兴得到任何帮助和/或 cmets。
【问题讨论】: