Here is slightly less verbose version

package Obj;
use Moose;
use Moose::Util::TypeConstraints;
use DateTime;
use DateTime::Format::MySQL;

class_type 'DateTime';

subtype 'MaybeDateTime' => as 'Maybe[DateTime]';

coerce 'MaybeDateTime'
   => from 'Str'
   => via {
       # 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 {
       return DateTime::Format::MySQL->parse_datetime($_)
   };

has 'date' => ( isa => 'MaybeDateTime', is => 'rw', coerce => 1 );

package main;

my $a = Obj->new(date => DateTime->new(year => 2000)); # DT
my $b = Obj->new(date => '0000-00-00 00:00:00'); # undef
my $c = Obj->new(date => '2000-10-10 00:00:00'); # DT

On Tue, Feb 16, 2010 at 5:25 AM, Karen Etheridge <p...@froods.org> 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 );
>
> # this generates "Attempt to free unreferenced scalar" error!
> #has date => ( is => 'rw', isa => 'Undef | DateTime', coerce => 1 );
>
> subtype 'DateTime' => as 'Object' => where { $_->isa('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;
>
> --
>                      A dozen, a gross, and a score,
>                      plus three times the square root of four,
>                      divided by seven,
>                      plus five times eleven,
>                      equals nine squared and no more!
>            .             .            .            .             .
> Karen Etheridge, ka...@etheridge.ca       GCS C+++$ USL+++$ P+++$ w--- M++
> http://etheridge.ca/                      PS++ PE-- b++ DI++++ e++ h(-)
>



-- 
Regards,
Mikhail

Reply via email to