p5-Mouse icon indicating copy to clipboard operation
p5-Mouse copied to clipboard

Coerce documentation is missing important fact that it must be requested in attribute definition.

Open bbkr opened this issue 2 years ago • 0 comments

By reading https://metacpan.org/pod/Mouse::Util::TypeConstraints documentation i felt into the trap and spent good amount of time trying to figure out why following code is not working:

package A;

use Mouse;
use Mouse::Util::TypeConstraints;

subtype 'MultiInt' => as 'ArrayRef[Int]';
coerce 'MultiInt' => from 'Int' => via { [ $_ ] };

has 'a' => ('is' => 'ro', 'isa' => 'MultiInt');

and A->new( 'a' => 1 ) was throwing me this error:

Attribute (a) does not pass the type constraint because: Validation failed for 'MultiInt' with value 1 at 
...

Fix:

This documentation page should mention, that coerce should be explicitly requested in attribute definition: has 'a' => ('is' => 'ro', 'isa' => 'MultiInt', 'coerce' => 1);. Good example is Moose documentation that says is explicitly: Moose will never try to coerce a value unless you explicitly ask for it. This is done by setting the coerce attribute option to a true value. While in Mouse this important piece of information is not mentioned in Mouse::Util::TypeConstraints nor Moose::Manual::Attributes doc.

bbkr avatar Apr 20 '22 12:04 bbkr