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