Re: Coercion nesting

[email protected] (Stevan Little)
Newsgroups perl.moose
Message-ID <[email protected]>
Dan,

I have to ponder this one, it would basically mean we need to wrap a  
loop around the coerce statement which would keep trying until it  
matched the type. I have concerns about the performance impacts of  
this, and of the possibility of unintended coercions happening since  
types/coercions are essentially global.

We have discussed a (deep_coerce => 1) option for attributes, which  
originally meant that it would coerce inside collections too (coerce  
the elements of an ArrayRef, or of a HashRef), but it could also mean  
"keep coercing until you cant anymore" too.

- Stevan

On Jan 25, 2008, at 2:21 PM, Dan Harbin wrote:

> Below I've included a snippet of my type constraints module where I
> declare my own personal type constraints and coercions.
>
> I'm trying to make it where I can have an accessor of type YAML, where
> I can assign it a string representing a file name.  This file name
> gets coerced into an InputFile, which gets coerced into a YAML.
>
> This gives me an error like so:
> Attribute (file) does not pass the type constraint (YAML) with
> 'config.yml' at Moose/Meta/Attribute.pm line 244
>
> Is there any way to chain or nest the constraints like I've tried  
> below?
>
> Thanks,
> Dan
>
> -------
>
> use Moose::Util::TypeConstraints;
> use IO::File;
> use YAML;
>
> subtype 'InputFile'
>   => as 'Object'
>   => where { $_->isa('IO::Handle') };
>
> coerce 'InputFile'
>   => from 'Str'
>   => via {
>     my $io = IO::File->new();
>     $io->open($_, 'r') or IOException->throw( error => "Unable to open
> file $_: $!" );
>     return $io;
>   };
>
> subtype 'YAML'
>   => as 'Ref';
>
> coerce 'YAML'
>   => from 'InputFile'
>   => via {
>     my $data = do{ local($/); $_->getline };
>     YAML::Load($data);
>   };
>
> 1;
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.