如何在Moose构造函数中检查所需参数的有效性?

时间:2013-10-20 00:23:01

标签: perl moose

这是肯定的非常简单的问题,但我还在学习,却找不到答案。

需要检查Moose对象构造函数提供的(必需)参数的有效性,例如:比如下一个例子:

use 5.016;
use warnings;

package My {
    use Moose;
    has 'mydir' => (
        is          => 'ro',
        isa         => 'Str',
        required    => 1,
    );
}

use File::Path qw(remove_tree);
package main {
    my @dirs = qw(./d1 ./d2);

    #ensure no one dir exists
    remove_tree($_) for ( @dirs );

    #create the first dir
    mkdir $dirs[0] or die;

    foreach my $dir( @dirs ) {
        my $m = My->new( mydir=>$dir );
        say "$dir ", defined($m) ? "" : "NOT", " ok";
    }
}

问题是:我应该添加到My包中以确保仅在所提供的My路径存在的情况下创建mydir对象?所以某处需要添加测试if -d ...

如何使用有效性检查定义属性mydir

主程序的通缉结果:

./d1 ok
./d2 NOT ok

1 个答案:

答案 0 :(得分:4)

您可以使用type constraint定义子类型。

使用它的语法糖由Moose::Util::TypeConstraints提供。

package My;
use 5.16.0;

use Moose;
use Moose::Util::TypeConstraints; # provides sugar below

subtype 'ExistingDir' => (
    as 'Str',
    where { -d $_ },
    message { 'The directory does not exist' }
    );

has 'mydir' => (
        is          => 'ro',
        isa         => 'ExistingDir',
        required    => 1,
    );

package main;

my $foo = My->new(mydir => 'perl'); # exists
say $foo->mydir();

my $bar = My->new(mydir => 'perlXXX'); # does not exist, so dies here...

输出:

>mkdir perl
>perl foo.pl

perl
Attribute (mydir) does not pass the type constraint because: The directory does not exist at ...