concrete
This commit is contained in:
62
lib/CW/Config.pm
Normal file
62
lib/CW/Config.pm
Normal file
@@ -0,0 +1,62 @@
|
||||
package CW::Config;
|
||||
|
||||
use Moo;
|
||||
|
||||
use Carp ();
|
||||
use YAML::Tiny;
|
||||
|
||||
has file => (
|
||||
is => 'ro',
|
||||
default => sub {
|
||||
'config.yml';
|
||||
}
|
||||
);
|
||||
|
||||
has _config => ( is => 'rw' );
|
||||
|
||||
sub get {
|
||||
my ( $self, @args ) = @_;
|
||||
|
||||
$self->_load_config unless $self->_config;
|
||||
|
||||
if ( @args > 1 ) { # Looking up nested args
|
||||
my $tar = $self->_config;
|
||||
for (@args) {
|
||||
Carp::croak( "Invalid config lookup: " . join( ' -> ', @args ) )
|
||||
unless $tar;
|
||||
$tar = $tar->{$_};
|
||||
}
|
||||
return $tar;
|
||||
}
|
||||
|
||||
if ( !@args ) { # No args, return config
|
||||
return $self->_config;
|
||||
}
|
||||
|
||||
my ($key) = @args; # One arg, get single config element
|
||||
my $val = $self->_config->{$key};
|
||||
|
||||
if ( ref($val) && ref($val) eq 'HASH' ) {
|
||||
|
||||
# If the value selected is a hash, return a new CW::Hash so we can chain gets
|
||||
my $next = CW::Config->new();
|
||||
$next->_config($val);
|
||||
return $next;
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
sub _load_config {
|
||||
my ($self) = @_;
|
||||
|
||||
my $file = $self->file;
|
||||
my $yaml_docs = YAML::Tiny->read($file);
|
||||
|
||||
Carp::croak("Config: $file didn't load properly!")
|
||||
unless $yaml_docs && $yaml_docs->[0];
|
||||
|
||||
$self->_config( $yaml_docs->[0] );
|
||||
}
|
||||
|
||||
1;
|
||||
Reference in New Issue
Block a user