attribute w/ coerce and trigger - trigger arguments

[email protected] (Charles Alderman)
Newsgroups perl.moose
Message-ID <[email protected]>
Hello,

Just started using Moose (love it).  I recently spent a little time  
struggling through an issue with trigger arguments for a coerced  
attribute.  So, I thought I'd post what I found here in case anyone  
else runs into it.

Actually, I'm not sure if I found an undocumented feature of Moose, or  
if it's a bug.  The docs say that a trigger is passed an updated value  
of the attribute.  What happens is that if the attribute has a  
coercion, the argument passed to the trigger hasn't been coerced.  So,  
technically, the argument isn't an updated value.  (At least, that's  
where my confusion came from.)

The coerced value is still available to the trigger through the  
attribute's accessor, so maybe having the non-coerced value also  
available is for the best.

For clarification, I included an example.

Thanks,
Charles Alderman
aldermania.com

Versions:
Moose - 0.40
Class::MOP - 0.54

--

 From the Moose perldoc:

The trigger option is a CODE reference which will be called after the  
value of the attribute is set. The CODE ref will be passed the  
instance itself, the **updated value** and the attribute meta-object  
(this is for more advanced fiddling and can typically be ignored).

--

Here's an example:
#This example is based on: Schwartz, R.L. "The Moose is Flying (part  
2)". LinuxMag Column 95 (Jul 2007)

package Mortgage;

use Moose;
use Moose::Util::TypeConstraints;

use DateTime;
use DateTime::Format::DateManip;
use Date::Manip;
Date_Init( 'TZ=US/Eastern' );

subtype 'DateTime'
   => as 'Object'
   => where { $_->isa('DateTime') };

coerce 'DateTime'
   => from 'Str'     => via { DateTime::Format::DateManip->parse_datetime($_) }
   => from 'HashRef' => via { DateTime->new(%$_) };

has 'closing_date' => (
   is => 'rw',
   isa => 'DateTime',
   coerce => 1,

   trigger => sub {
     my ( $self, $val, $meta ) = @_;
     print $self->closing_date->isa('DateTime') ? 'yes' : 'no';  # yes
     print $val->isa('DateTime')                ? 'yes' : 'no';  # no???
   }
);

1;

package main;

my $mtg = Mortgage->new( closing_date => 'yesterday' );
print $mtg->closing_date->isa('DateTime') ? 'yes' : 'no';  # yes
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.