正确的方式定义和转换Moose属性类型

时间:2013-10-27 20:23:06

标签: perl moose

有:

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都应该返回祝福{{ 1}}

当我尝试将定义扩展到下一个时:

Path::Class::Dir

它不起作用,仍然需要在has 'path' => ( is => 'ro', isa => 'Path::Class::Dir|Str', #allowing both attr types required => 1, ); 内自动“内部地”将Str转换为Path::Class::Dir ...

有人可以给我一些提示吗?

编辑:根据Oesor的提示我找到了比我需要的东西:

package MyPath

但仍然不知道如何正确使用它......

请提供更多提示?

2 个答案:

答案 0 :(得分:5)

你正在寻找类型coersion。

use Moose;
use Moose::Util::TypeConstraints;
use Path::Class::Dir;

subtype 'Path::Class::Dir',
   as 'Object',
   where { $_->isa('Path::Class::Dir') };

coerce 'Path::Class::Dir',
    from 'Str',
        via { Path::Class::Dir->new($_) };

has 'path' => (
    is       => 'ro',
    isa      => 'Path::Class::Dir',
    required => 1,
    coerce   => 1,
);

答案 1 :(得分:0)

提示 - 寻找如何强制价值:

https://metacpan.org/pod/Moose::Manual::Types

相关问题