Moose: enter parameters into the construct

I have a filename attribute that has an attached check. Now that the file name is not specified at build time, I want to read it from the configuration file.

subtype 'filename' => as 'Str' => where { -r $_ } => message { "$_ is not a readable file" }; has 'students_file' => ( is => 'rw', isa => 'filename', default => '' ); has 'teachers_file' => ( is => 'rw', isa => 'filename', default => '' ); 

The problem is that BUILD seems to start after checking. All BUILDARGS examples seem to handle a different way of building an object.

So where should I read the configuration and set the attribute?

+4
source share
1 answer

Give the teachers_file and students_file builder (or built-in default subs) methods that install them from the configuration file. The builder is launched only if these attributes are not provided as constructor keys (unless you use init_arg => undef so that they are not set in the constructor).

If your config is a native attribute, with a builder that reads the configuration file, then you have a problem with the ordering between config and teachers_file and students_file . You can solve this problem by creating teachers_file and students_file lazy attributes that guarantee that they will not try to construct before the config attribute. However, you can verify that the "foo is not readable file" error is raised as early as possible during build, and not the first time the attribute is used. You can get around this by adding

 sub BUILD { my $self = shift; $self->teachers_file; $self->students_file; } 

which ensures that these attributes are read once (and built) before the constructor returns.

+7
source

All Articles