Question

Can any provide some guidance on using MooseX::Params::Validate validated_hash method and using a default ArrayRef? I was hoping it was similar to the declaration using Moose's "has" attributes but they seem to differ.

use Moose;
use MooseX::Params::Validate;
use Data::Dumper;

has 'arg1' => (
    is => 'ro',
    isa => 'ArrayRef[Str]',
    lazy => 1,
    default => sub { return ['blah1', 'blah2', 'blah3'] },
    reader => 'get_arg1'
    );

sub testsub {
    my $self = shift;
    my %args = validated_hash(
        \@_,
        arg1 => {
            is         => 'rw',
            isa        => 'ArrayRef[Str]',
            required   => 0,
            default    => sub {return ['blah1', 'blah2', 'blah3']}
            }
        );
    print Dumper($args{'arg1'});

    return 0;
    }

no Moose;

__PACKAGE__->meta->make_immutable;

1;

Running the testsub method returns:

$VAR1 = sub { "DUMMY" };

If I change the method to use the Moose attribute:

        arg1 => {
            is         => 'rw',
            isa        => 'ArrayRef[Str]',
            required   => 0,
            default    => $self->get_arg1}
            }

Then it outputs the expected ArrayRef content:

$VAR1 = [
      'blah1',
      'blah2',
      'blah3'
    ];

The goal is to eventually make the "testsub" method a Moose::Role.

Was it helpful?

Solution

For MooseX::Params::Validate, use:

default    => ['blah1', 'blah2', 'blah3'],

The reasons that Moose attributes use a coderef here don't really apply to MooseX::Params::Validate, so MooseX::Params::Validate has never supported using a coderef to produce a default.

This probably ought to be better documented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top