It is possible to use an after modifier in a Role for a required attribute that is populated in the consuming class via a builder method?
package A::Role;
use Moose::Role;
use IO::File;
use Carp;
requires 'properties_file';
after 'properties_file' => sub {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
};
Consuming class:
package A::B::C;
use Moose;
use Carp;
use Moose;
use Carp;
use HA::Connection::SSH;
use constant {
...
};
has 'properties_file' => ( is => 'ro',
isa => 'Str',
builder => '_build_current_data');
with 'A::Role';
sub _build_current_data { ... }
To answer your question: Yes you can. You've already done the crucial part which was to consume the role after declaring the attribute so that the accessor method is generated.
So the code that you supplied would execute in the sequence that you would expect:-
my $c = A::B::C->new;
# 'properties_file' is built by _build_current_data()
my $filename = $c->properties_file;
# _check_prop_file() and _read_file() are executed (but before $filename is assigned)
However, it does seem strange that you invoke the checking and reading of the properties file by getting properties_file
. If you just want the properties file to be checked and read automatically after construction, the role could supply a BUILD
method to be consumed into the class. (BUILD
is executed after construction, so properties_file
will be initialised already.)
sub BUILD {
my $self = shift;
$self->_check_prop_file();
$self->_read_file();
return;
}