Re: Multiple coercions ?

[email protected] (Charles Alderman)
Newsgroups perl.moose
Message-ID <[email protected]>
> Now - and that's where the issue gets in the scene - if I add another
> coercion for the DateTime subtype, but from another source, it won't
> work :

Are you sure you haven't defined the coercion to "DateTime" from "Int"  
somewhere else?

This works for me:

{
     package Foo;
     use Moose;
     use Moose::Util::TypeConstraints;

     subtype 'Date'
       => as 'Str'
       => where { /^\d\d\d\d-\d\d-\d\d$/ };

     subtype 'DateTime'
       => as 'Str'
       => where { /^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/ };

     coerce 'DateTime'
       => from 'Date'
       => via { "$_ 00:00:00" };

     coerce 'DateTime'
       => from 'Int'
       => via { '2008-09-24 00:00:00' };

     has 'date' => (
         is => 'rw',
         isa => 'Date',
     );

     has 'date_time' => (
         is => 'rw',
         isa => 'DateTime',
         coerce => 1,
     );
}

{

   my $f = Foo->new;
   $f->date_time(1234);
   $f->date_time('2008-09-24');

}

Thanks,
Charles Alderman
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.