On Thu, Dec 24, 2009 at 4:55 PM, Mike Friedman <fri...@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

> On Thu, Dec 24, 2009 at 4:04 PM, Sir Robert Burbridge
> <rburb...@cisco.com> wrote:
>> Hey all,
>>
>> I'm very new to Moose, building my first app that uses more than just "has
>> foo => (isa=>'Str', is=>'rw')"-level features.
>>
>> I am trying to make a property like this:
>>
>>   has foo => (isa=>'Str', is=>'rw');
>>
>> in which the property undergoes a transformation more or less like,
>>
>>   $self->{'foo'} =~ s/\W+/_/gs;
>>
>> such that this would be true:
>>
>>   ...
>>   $obj->foo("one two ?three");
>>   print $obj->foo, "\n";   ### prints: "one_two_three"
>>
>> What's the best way to accomplish that?  Is that even something
>> appropriately put on Moose?  Can someone point me to where to look in the
>> manual or cookbook (I've looked already, but I don't know what I'm looking
>> for, really).
>>
>> Thanks!
>>
>> -Sir Robert
>>
>

Reply via email to