Re: Multiple coercions ?
[email protected] (Charles Alderman)
| Newsgroups | perl.moose |
|---|---|
| Message-ID | <[email protected]> |
I tried running that code. My output: % perl multiple_coercions.t ok 1 - date set to 2008-09-12 ok 2 - coerce date_time from date ok 3 - date_time correctly coerced ok 4 - coerce from Int 1..4 Also: % perl -Moose -e"print $Moose::VERSION" 0.54 Thanks, Charles Alderman ----- Original Message ----- From: Alexis Sukrieh <[email protected]> Sent: Wed, 24 Sep 2008 16:57:11 +0200 Re: Re: Multiple coercions ? > Alexis Sukrieh a écrit : >> Find attached the test script: > > Hmm, sorry, looks like the attachment gets droped by the ML. > Here is the pure paste: > > > $ cat multiple_coercions.t > > use Test::More 'no_plan'; > use strict; > use warnings; > > sub time_to_datetime($) { > my $time = shift; > my ($sec, $min, $hour, $day, $mon, $year) = localtime($time); > $mon++; > $year += 1900; > $sec = sprintf('%02d', $sec); > $min = sprintf('%02d', $min); > $hour = sprintf('%02d', $hour); > $mon = sprintf('%02d', $mon); > $day = sprintf('%02d', $day); > return "${year}-${mon}-${day} ${hour}:${min}:${sec}"; > } > > # Types & Coercions > 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 'Int' > => via { time_to_datetime($_) }; > > coerce 'DateTime' > => from 'Date' > => via { "$_ 00:00:00" }; > > { > package Foo; > use Moose; > > has 'date' => ( > is => 'rw', > isa => 'Date', > ); > > has 'date_time' => ( > is => 'rw', > isa => 'DateTime', > coerce => 1, > ); > } > > # fixtures > my $date = '2008-09-12'; > my $date_time = '2008-09-12 00:00:00'; > > my $o = Foo->new; > is( $date, $o->date($date), "date set to $date" ); > ok( $o->date_time($o->date), 'coerce date_time from date' ); > is( $date_time, $o->date_time, 'date_time correctly coerced' ); > > ok( $o->date_time( time ), 'coerce from Int' );