On Mon, Feb 15, 2010 at 04:25:54PM -0800, Karen Etheridge wrote:
> 
> I'm having difficulty getting a type coercion to work that involves Maybes.
> I've looked at the "deep coercion" section of Moose::Manual::Types, and I'm
> not sure what I'm missing to get this to work?
> 
> e.g. I'm running
> 
> perl -MData::Dumper -MObject -MDateTime -I. -wle'my 
> $o=Object->new(date=>"0000-00-00 00:00:00"); print Dumper($o)'
> 
> against this module, Object.pm:
> 
> package Object;
> use Moose;
> use Moose::Util::TypeConstraints;
> use DateTime;
> use DateTime::Format::MySQL;
> 
> has date => ( is => 'rw', isa => 'MaybeDateTime', coerce => 1 );

I'm not sure what problem you're having, since you didn't post the
error message, but you probably need the attribute definition to happen
after the types are defined... pretty sure this would assume you have a
class named 'MaybeDateTime'.

> # this generates "Attempt to free unreferenced scalar" error!
> #has date => ( is => 'rw', isa => 'Undef | DateTime', coerce => 1 );

If you could turn this issue into an actual failing test, that would be
really helpful.

> subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };

Also, this is equivalent to "class_type 'DateTime'".

> subtype 'MaybeDateTime'
>     => as 'Maybe[Object]'
>     => where { $_->isa('DateTime') or not defined $_ };
> 
> coerce 'MaybeDateTime'
>     => from 'DateTime'
>     => via { return $_ };
> 
> coerce 'MaybeDateTime'
>     => from 'Str'
>     => via {
>         print "### calling Str->MaybeDateTime coercion\n";
>         # check for retarded mysql 4.x null times
>         return if $_ eq '0000-00-00 00:00:00';
>         return DateTime::Format::MySQL->parse_datetime($_);
>     };
> 
> coerce 'DateTime'
>     => from 'Str'
>     => via {
>         print "### coercing Str $_ into DateTime\n";
>         return DateTime::Format::MySQL->parse_datetime($_);
>     };
> 
> 1;

-doy

Reply via email to