How to verify the correct argument in the Moose constructor?

This is a very simple question, but I was still studying and could not find the answer.

You need to check the validity of the provided (required) argument for the Moose object constructor, for example. as in the following example:

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";
    }
}

Question: what should I add to the package Myto ensure that the object My is created only if the provided path mydirexists? So somewhere you need to add a test if -d ....

How to define a mydirvalidation attribute ?

The result of the main program is required:

./d1 ok
./d2 NOT ok
+4
source share
1 answer

.

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 ...
+4

All Articles