【问题标题】:Correct way define and convert the Moose attribute type正确定义和转换 Moose 属性类型的方法
【发布时间】: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,
);

但还是不知道如何正确使用它...

请提供更多提示?

【问题讨论】:

    标签: perl moose


    【解决方案1】:

    您正在寻找类型强制。

    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,
    );
    

    【讨论】:

    • 您的subtype 'Path::Class::Dir' ... 声明可以更自然地写成class_type 'Path::Class::Dir';
    【解决方案2】:

    提示——寻找如何强制值:

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

    【讨论】:

    • 能否再添加一些提示?我编辑了我的问题...(可能还需要 1-2 行 - 你能给我一个答案吗?:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2016-05-13
    • 2017-02-26
    • 1970-01-01
    • 2011-01-19
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多