in reply to Moose: Problems subtyping a coerced subtype

Moose won't do coersion unless you request it, so, at the least, you would need:

has file => ( isa => 'ExistingFile', is => 'ro', required => 1, coerce + => 1 );

However, that doesn't work for me either, complaining:

You cannot coerce an attribute (file) unless its type (ExistingFile) h +as a coercion at /tmp/test.pl line 26

Apparently, coersion is not inherited by subtypes by design, so you will need to duplicate the coersion.

subtype 'ExistingFile' => as 'AFile' => where { say "In subtype where clause: $_[0]"; -f $_[0] }, message { "$_[0] does not exist" }; coerce 'ExistingFile' => from 'Str' => via { file($_) }; has file => ( isa => 'ExistingFile', is => 'ro', required => 1, coerce + => 1 );

Note: You can reduce the code duplicationg using:

for my $ftype (qw/ AFile ExistingFile /) { coerce $ftype => from 'Str' => via { file($_) }; }

Good Day,
    Dean

Replies are listed 'Best First'.
Re^2: Moose: Problems subtyping a coerced subtype
by BaldManTom (Friar) on Jan 21, 2015 at 18:04 UTC

    Thanks duelafn, and especially thanks for the link. I didn't know that coercions were not inherited. Ah well. Since the subtypes are in different files, I'll either need to duplicate code or make other arrangements.

    Thanks again, I appreciate you taking time to help.

      You shouldn't need to duplicate code; as via can take a code ref in addition to a block, define an actual subroutine in the parent class and grab its reference via fully qualified package; or use introspection to traverse the coercion map (Moose::Meta::TypeCoercion). The former will be more obvious from casual inspection, and the latter would be more robustly maintainable.

      Neither is particularly elegant, though.


      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

        Good to know, kennethk. Thanks for the info. I'll look into both suggestions. Thanks for taking the time to help.