It works, but passing an attribute name to the trait and then passing an instance around seems not very elegant to me. Is there any other way to access the class instance from within an attribute trait method?
I would suggest actually that you not pass an attribute name, but instead pass a method name. Then if you put the method name into a common key like 'parameter_callback' instead of the more specific 'attr_valid_domain' you could likely move all the code up into the My::Config role. Here is an (untested) example of what I am talking about:
This has a couple benefits:with My::Config; ## some runtime information, eventually for the trait's method has validDomain => ( isa => 'Str', is => 'rw', ); has alarmMailsTo => ( traits => ['ConfigEmail'], conf_key => 'ALARM_MAILS_TO' parameter_callback => 'validDomain' ## give a method name isa => 'ArrayRef[Str]', is => 'rw', ); .. ## Class role role My::Config { method load() { .. ## $attr is a Moose::Meta::Attribute my $parameter_callback = $attr->parameter_callback; $attr->parse($configString, $self->$parameter_callback()); .. } } ## Base Attribute Trait role My::Config::AttrBase { has parameter_callback => ( isa => 'Str', is => 'rw', required => 1, ); } ## Attribute Trait role My::Config::ConfigEmail with My::Config::AttrBase { method parse($value!, @parameters) { # now this is a more generic API } }
In reply to Re^5: Moose: Where to define a method required by an attribute trait?
by stvn
in thread Moose: Where to define a method required by an attribute trait?
by maxhq
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |