Paul,
You cannot attached coercions to parameterized types directly. Try
this ..
class_type 'DateTime';
# alias the Maybe[DateTime] type ...
subtype 'MightBeADateTimeObjectOrMightNot' as 'Maybe[DateTime]';
# insert the rest of your code here ...
This should do the trick as that is how we do it for ArrayRef[`a] and
HashRef[`a] types, although I have to admit I never actually tried
this on a Maybe[`a] type so I can't really say for sure.
- Stevan
On Jul 10, 2009, at 12:24 AM, Paul Fenwick wrote:
G'day Moosers,
I'm writing a piece of code where I'm making use of the
Maybe[DateTime]
construct. An event may not have occurred (in which case we want
undef), or
it may have (in which case we want a DateTime object). I'm sucking
in a
hunk of XML which represents the dates, and I have code that can
convert a
hunk of XML (represented in a hash structure) into a DateTime object
or undef:
use Moose::Util::TypeConstraints;
use DateTime;
use DateTime::Format::Natural;
class_type 'DateTime';
coerce 'Maybe[DateTime]' => from 'HashRef' => via {
warn "\n\n\n*** COERCING DATETIME ***\n\n\n";
if ($_->{nil} eq "true") { return undef; }
return DateTime::Format::Natural->new->parse_datetime($_-
>{content})
};
When trying to run this code, Moose is sad that it doesn't know
about the
Maybe[DateTime] type:
Cannot find type 'Maybe[DateTime]', perhaps you forgot to load it
at
/usr/lib/perl5/site_perl/5.10/Moose/Util/TypeConstraints.pm line
506
If I simply try to coerce DateTime, then I can't legitimately return
undef,
because that fails the type constraint. If I declare `class_type
'Maybe[DateTime]'` then the coerce code runs, but Moose still
complains that
the type constraint fails:
Attribute (last_blog_post_at) does not pass the type constraint
because:
Validation failed for 'Maybe[DateTime]' failed with value undef
(not isa
Maybe[DateTime]) at
/usr/lib/perl5/site_perl/5.10/Moose/Meta/Attribute.pm line 753
FWIW, the attribute in question looks like this:
has last_blog_post_at => ( isa => 'Maybe[DateTime]', coerce => 1 );
I'm using Moose 0.87.
Any advice would be appreciated.
Many thanks,
Paul
--
Paul Fenwick <p...@perltraining.com.au> | http://perltraining.com.au/
Director of Training | Ph: +61 3 9354 6001
Perl Training Australia | Fax: +61 3 9354 2681