develooper Front page | perl.moose | Postings from December 2009

Re: Filtering property values

Thread Previous
From:
Sir Robert Burbridge
Date:
December 24, 2009 19:57
Subject:
Re: Filtering property values
Message ID:
4B343818.2020106@cisco.com
On 12/24/2009 05:34 PM, Chris Prather wrote:
> On Thu, Dec 24, 2009 at 4:55 PM, Mike Friedman<friedo@friedo.com>  wrote:
>    
>> You should be able to do this with triggers. For example:
>>
>> has foo =>  ( isa =>  'Str', is =>  'rw', trigger =>  \&_munge_foo );
>>
>> sub _munge_foo {
>>     my ( $self, $new_foo, $old_foo ) = @_;
>>
>>     $new_foo =~ s/\W+/_/gs;
>>     $self->{foo} = $new_foo;
>> }
>>
>> The trigger will be called every time foo is set, including in the constructor.
>>
>>
>> Mike
>>      
> A Trigger really is the wrong way to go about this. While yes this
> will work it's not considered "best practice".
>
> What you *do* want is a TypeConstraint and a Coercion.
>
> use Moose::Util::TypeConstraints;
>
> subtype MyAppCleanStr =>  as Str =>  where { $_ !~ /\W+/gs }; # make a
> TypeConstraint based on what you want
> coerce MyAppCleanStr =>  from Str =>  via { $_ =~ s/\W+/_/gs }; # define
> how to convert dirty Str to a Clean Str
>
> has foo =>  ( isa =>  'MyAppCleanStr', is =>  'rw', coerce =>  1): # tell
> Moose you want to coerce for this attribute.
>
> -Chris
>    
Great -- thanks, guys.  I'll read up on both of those.

-Sir


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About