Subject: | Coercion is done on non-required, non-provided keys |
Hi,
I ran into an annoying bug with MX:P:V, demonstrated by the attached
script. In short, due to this line in MX:P:V->validate_hash:
$args{$_} = $spec{$_}{constraint}->coerce( $args{$_} )
for grep { $spec{$_}{coerce} } keys %spec;
coercion is done regardless, even if the key is specified is optional
and/or not even provided. So with a spec like:
key => { isa => .., optional => 1, coerce => 1 }
coercion's always called, and will throw an exception on failure, before
the spec is even validated by P:V.
Subject: | x.pl |
package Foo;
use Moose;
use MooseX::Params::Validate;
use MooseX::Types::URI qw[Uri];
sub bar {
$DB::single = 1;
my ( $self, %args ) = validated_hash(
\@_,
url => { isa => Uri, default => '', coerce => 1 },
name => { isa => 'Str', optional => 1 },
);
return join ' ', keys %args;
}
package main;
my $foo = Foo->new;
warn "No args: " . (eval { $foo->bar } || $@);
warn "Just url: " . (eval { $foo->bar( url => 'http://example.com' )} || $@);
warn "Just name: ". (eval { $foo->bar( name => $$ ) } || $@);
__END__
No args: The 'url' parameter (undef) to Foo::bar did not pass the 'checking type constraint for MooseX::Types::URI::Uri' callback
at /home/demo/perl/5.10/lib/site_perl/5.10.0/MooseX/Params/Validate.pm line 56
MooseX::Params::Validate::validated_hash('ARRAY(0x9b0fc40)', 'url', 'HASH(0x9b04078)', 'name', 'HASH(0x99931e0)') called at tmp/x.pl line 8
Foo::bar(undef) called at tmp/x.pl line 20
eval {...} called at tmp/x.pl line 20
Just url: url at tmp/x.pl line 21.
Just name: The 'url' parameter (undef) to Foo::bar did not pass the 'checking type constraint for MooseX::Types::URI::Uri' callback
at /home/demo/perl/5.10/lib/site_perl/5.10.0/MooseX/Params/Validate.pm line 56
MooseX::Params::Validate::validated_hash('ARRAY(0x9b0f880)', 'url', 'HASH(0x9434668)', 'name', 'HASH(0x9941f68)') called at tmp/x.pl line 8
Foo::bar(undef, 'name', 12583) called at tmp/x.pl line 22
eval {...} called at tmp/x.pl line 22