Thank you Oliver and Stevan for your help.
I have finally made the following module that works fine:
(That line which uses month_name() is there for testing only.)
package Foo;
use Moose;
use Moose::Util::TypeConstraints;
use DateTime;
use DateTime::Format::Natural;
class_type('DateTime');
subtype 'DT' => as 'Maybe[DateTime]';
coerce 'DT' => from 'Str' => via
{DateTime::Format::Natural->new->parse_datetime($_)};
has start => (is => 'rw', isa => 'DT', coerce => 1);
package main;
my $foo = Foo->new;
my $date;
#$date = "2010-05-01";
#$date = DateTime->now;
$foo->start($date);
print $foo->start->month_name;
--
Octavian
----- Original Message -----
From: "Oliver Charles" <oliver.g.char...@gmail.com>
To: "Octavian Rasnita" <orasn...@gmail.com>
Cc: <moose@perl.org>
Sent: Tuesday, June 15, 2010 12:39 AM
Subject: Re: Coercing a type that can be undef
(Sorry, forgot to reply to all)
On Mon, Jun 14, 2010 at 10:13 PM, Octavian Rasnita <orasn...@gmail.com>
wrote:
Hello,
I am trying to create a module that accepts a string property as
2010-05-01 and coerces it to DateTime by default, but that property might
be also undef.
I have tried:
If you're happy using MooseX::Types, this is fairly easy:
package Foo;
use Moose;
use DateTime;
use DateTime::Format::Natural;
use MooseX::Types -declare => [qw( DT )];
use MooseX::Types::Moose qw( Maybe Str Undef );
subtype DT, as Maybe[class_type('DateTime')];
coerce DT,
from Str, via { DateTime::Format::Natural->new->parse_datetime($_) };
has start => (is => 'rw', isa => DT, coerce => 1);
package main;
my $foo = Foo->new;
my $date;
#$date = '2010-05-01';
$foo->start($date);
print $foo->start->month_name;
The code still errors, because you can't call month_name on undef, but
that's your problem ;)
--
Oliver Charles / aCiD2
__________ Information from ESET NOD32 Antivirus, version of virus
signature database 5196 (20100614) __________
The message was checked by ESET NOD32 Antivirus.
http://www.eset.com
__________ Information from ESET NOD32 Antivirus, version of virus signature
database 5197 (20100615) __________
The message was checked by ESET NOD32 Antivirus.
http://www.eset.com