On Mon, Feb 16, 2009 at 1:09 PM, Chad Davis <chad.a.da...@gmail.com> wrote:
> Is someone still following that might also have a good solution for > preventing unwanted values from getting into an attribute? Well my first thought was you wanted an initializer but looking at my own notes for an outstanding doc patch I promised they don't get fired on setting an attribute just on creating an attribute. So I then remembered that you could pass something other than a string to writer and I though possibly that was a subref, in the Class::MOP documentation it says: The accessor, reader, writer, predicate and clearer keys can contain either; the name of the method and an appropriate default one will be generated for you, or a HASH ref containing exactly one key (which will be used as the name of the method) and one value, which should contain a CODE reference which will be installed as the method itself. which says that you can write: has myattr => ( isa => 'Str', accessor => { myattr => sub { my ( $self, $value ) = @_; if ( defined $value ) { ( $self->{myattr} = $value ) =~ s/\s//g } return $self->{myattr}; }, }, ); to get to where you want to be. I can think that a patch to Class::MOP::Attribute to allow CODE refs as well as HASH refs might make this situation cleaner ... but this should work in the current code. Here's an example that I tested: package Class; use Moose; has foo => ( accessor => { foo => sub { my ( $s, $v ) = @_; $s->{foo} = $v + 1 } } ); my $o = Class->new; $o->foo(1); say $o->dump