I'm new to using Moose, but I was wondering how I can load values from a configuration file and then exposing those values as properties of my 'config' object where the attributes are the configuration names in the configuration file.
For example,
The configuration file might contain:
server:mozilla.org
protocol:HTTP
So I'd like my config object to have a 'server' attribute with a value of 'mozilla.org' and a protocol attribute with a value of 'HTTP'.
Right now my understanding is that I have to explicitly name the attributes with a
has 'server' => ( is => 'ro', isa => 'Str', default => 'mozilla.org' );
type of entry in my Config.pm file.
How do I dynamically create these so that the configuration file can change without having me rewrite the Config.pm each time that it does?
TIA!
This isn't quite what you asked for, but you can get a config
attribute that's a hash reference by using BUILDARGS
to populate the config info at the time of creation. Assuming that the lines of your config file consist of key-value pairs separated by :
, something like this should work:
package My::Module;
use Moose;
has 'config'=>(isa=>'HashRef[Str]',is=>'rw',required=>1);
around BUILDARGS=>sub
{
my $orig=shift;
my $class=shift;
my $args=shift; #other arguments passed in (if any).
my %config_hash=();
open(my $read,"<","config_file") or confess $!;
while(<$read>)
{
chomp;
my @array=split /:/;
$config_hash{$array[0]}=$array[1];
}
close($read);
$args->{config}=\%config_hash;
return $class->$orig($args);
};
no Moose;
1;
With minimal effort, it's also easy to have additional attributes to specify the name and path of the config file along with the delimiter. These could be accessed inside of BUILDARGS
as, eg, $args->{config_file}
and $args->{config_delimiter}
.
That's such an obvious idea, it has been implemented already several times.
- MooseX::ConfigFromFile
- MooseX::Configuration
- MooseX::SimpleConfig
Also see
- MooseX::App
- MooseX::App::Cmd
- MooseX::Runnable
which map command-line options to attributes, which you most likely also want.