How can I access the attributes of my object in forcing Musa?

I want to force Str to a DBIx :: Class :: Row object for an attribute in my Moose class. To do this, I need to do a DBIC lookup to find the string. I want to push an error on the ArrayRef attribute if the search failed.

I am currently passing a schema as an attribute to my class.

Forced, it seems that I cannot access the object, so I can not click on the arrayref attribute of the error or use the schema object to perform my search.

An alternative that I tried was to use "around" to find and set the attribute during installation, but this, of course, is not called when the attribute value is passed through the constructor.

Is this possible, or does someone have an alternative implementation to do what I want to achieve?

+4
source share
1 answer

You can catch and mutate the value that is stored when passing to the constructor with an attribute initializer. (However, it only starts when the attribute is set in the constructor, and not at any other time.) The documentation for initializers can be found in Class :: MOP ::. Attribute

Since this only catches cases when the attribute is set through the constructor, you still need to catch other cases when the attribute is set. This can be done using the method modifier, as you said, but you can combine the two methods into one method, wrapped around auto-generated access:

has my_attr => ( is => 'rw', isa => 'DBIx::Class::Row', initializer => 'my_attr', ); # my_attr is the autogenerated accessor - we method-modify it to mutate the # value being set, and catch cases where it is called as an initializer. # called for reads, writes, and on initialization at construction time around 'my_attr' => sub { my $orig = shift; my $self = shift; # value is not defined if being called as a reader # setter and attr are only defined if being called as an initializer my ($value, $setter, $attr) = @_; # the reader behaves normally return $self->$orig if not @_; # convert the string to the row object my $row = $self->convert_str_to_row_obj($value); # if called as an initializer, set the value and we're done return $setter->($row) if $setter; # otherwise, call the real writer with the new value $self->$orig($row); }; 
+4
source

Source: https://habr.com/ru/post/1341282/


All Articles