in reply to Prepend a Moose attribute when changed
Hi, what you are looking for is a coercion. (I'd also recommend using Type::Tiny for type constraints).
This can be done in Moose:
... but IMHO it's much simpler (as are most things) in Moo:use strict; use warnings; use feature 'say'; package MyClass { use Moose; use Types::Standard 'Str'; has foo => ( is => 'rw', isa => Str->where(sub {/^bar\./})->plus_coercions(Str, sub +{'bar.' . $_}), coerce => 1, ); } my $obj = MyClass->new( foo => 'baz' ); say $obj->foo; # 'bar.baz $obj->foo('qux'); say $obj->foo; # 'bar.qux' __END__
use strict; use warnings; use feature 'say'; package MyClass { use Moo; use Types::Standard 'Str'; has foo => ( is => 'rw', isa => Str, coerce => sub {'bar.' . shift}, ); } my $obj = MyClass->new( foo => 'baz' ); say $obj->foo; # 'bar.baz' $obj->foo('qux'); say $obj->foo; # 'bar.qux' __END__
Hope this helps!
|
|---|