【发布时间】:2013-10-27 20:23:05
【问题描述】:
有:
package MyPath;
use strict;
use warnings;
use Moose;
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir',
required => 1,
);
1;
但是想用两种方式创建这个对象,比如:
use strict;
use warnings;
use MyPath;
use Path::Class;
my $o1 = MyPath->new(path => dir('/string/path')); #as Path::Class::Dir
my $o2 = MyPath->new(path => '/string/path'); #as string (dies - on attr type)
当使用 'Str' 调用它时 - 想要在 MyPath 包中将其内部转换为 Class::Path::Dir,因此,$o1->path 和 $o2->path 都应该返回祝福 Path::Class::Dir
当我尝试将定义扩展到下一个时:
has 'path' => (
is => 'ro',
isa => 'Path::Class::Dir|Str', #allowing both attr types
required => 1,
);
它不起作用,仍然需要在 package MyPath 内部自动将 Str 转换为 Path::Class::Dir...
有人能给我一些提示吗?
编辑:根据我发现的 Oesor 的提示,我需要一些类似的东西:
coerce Directory,
from Str, via { Path::Class::Dir->new($_) };
has 'path' => (
is => 'ro',
isa => 'Directory',
required => 1,
);
但还是不知道如何正确使用它...
请提供更多提示?
【问题讨论】: