Argument for salmon builder routine

Currently, I am passing a construction method to all objects that extend one of my base classes. The problem I am facing is that I need all objects to either read the attribute of themselves or be passed to the value.

# In Role: has 'const_string' => ( isa => 'Str', is => 'ro', default => 'test', ); has 'attr' => ( isa => 'Str', is => 'ro', builder => '_builder', ); requires '_builder'; # In extending object - desired 1 sub _builder { my ($self) = shift; # $self contains $self->const_string } # In extending object - desired 2 sub _builder { my ($arg1, $arg2) = @_; # $args can be passed somehow? } 

Is this possible now or will I have to do it differently?

+6
perl moose
source share
2 answers

You cannot pass arguments to attribute assembly methods. They are automatically called by the internal elements of Moose and only one argument is passed - the object reference itself. The builder should be able to regain his value based on what he sees in $self , or anything else in the environment to which he has access.

What arguments would you like to convey to the builder? Can you instead pass these values ​​to the constructor of the object and store them in other attributes?

 # in object #2: has other_attr_a => ( is => 'ro', isa => 'Str', ); has other_attr_b => ( is => 'ro', isa => 'Str', ); sub _builder { my $self = shift; # calculates something based on other_attr_a and other_attr_b } # object #2 is constructed as: my $obj = Class2->new(other_attr_a => 'value', other_attr_b => 'value'); 

Also note that if you have attributes built on the basis of other attribute values, you must define them as lazy , otherwise the default collectors / values ​​will be executed immediately when building the object and in undefined order. Setting them lazy will delay their determination until they are needed.

+12
source share

You can do something like this:

 has 'attr' => ( isa => 'Str', is => 'ro', builder => '_pre_builder', ); sub pre_builder { _builder(@_, 'your_arg'); } 
0
source share

All Articles