Config::Tree::File - Read configuration tree from a YAML file


Config-Tree documentation Contained in the Config-Tree distribution.

Index


Code Index:

NAME

Top

Config::Tree::File - Read configuration tree from a YAML file

SYNOPSIS

Top

 # in config.yaml:
 foo:
   bar: 2
   baz: 3

 # in script.pl:

 use Config::Tree::File;

 my $conf = Config::Tree::File->new(
     path  => '/path/to/config.yaml',
     # watch => 10, # currently not implemented
     # schema => ...,
     # when_invalid => ...,
     # include_path_re => qr/.../,
     # exclude_path_re => qr/.../,
     ro => 0,
 );
 my $val = $conf->get('/foo/bar'); # 2
 $conf->cd('/foo');
 $conf->set('bar', 10); # same as set('/foo/bar', 10);
 $conf->save(); # writes back to file

DESCRIPTION

Top

ATTRIBUTES

Top

METHODS

Top

new(%args)

Construct a new Config::Tree::File object. Arguments.

set($path, $val)

Set config variable.

Will not write to file until save() is called.

save()

Save config variable to file.

If schema is specified, config tree will be validated first and an error will be thrown if the config does not validate.

SEE ALSO

Top

Data::Schema, Config::Tree::Base

AUTHOR

Top

Steven Haryanto, <stevenharyanto at gmail.com>

COPYRIGHT & LICENSE

Top


Config-Tree documentation Contained in the Config-Tree distribution.
package Config::Tree::File;

use Moose;
extends 'Config::Tree::BaseFS';

has _mtime => (is => 'rw');
has _tree => (is => 'rw');
has _loaded => (is => 'rw', default => 0);

sub BUILD {
    my ($self) = @_;
    # immediately load
    $self->get_tree_for('/');
    $self->name("file ".$self->path) unless $self->name;
}

sub _load_file {
    my ($self) = @_;
    my $res = $self->_safe_read_yaml("");
    die "config must be hashref" unless ref($res) eq 'HASH';
    $res;
}

sub _get_tree {
    my ($self) = @_;
    unless ($self->_loaded) {
        if (-e $self->path) {
            my $res = $self->_load_file();
            $self->_tree($res);
            $self->_mtime((stat $self->path)[9]);
        } elsif ($self->must_exist) {
            die "config file doesn't exist";
        } else {
            $self->_tree(undef);
            $self->_mtime(-1);
        }
        $self->_loaded(1);
    }
    ($self->_tree, $self->_mtime);
}

sub _format_validation_error {
    my ($self, $res) = @_;
    sprintf("%sconfig file `%s` has %d error(s): `%s`",
            ($self->modified ? "modified " : ""),
            $self->path,
            scalar(@{ $res->{errors} }),
            join(", ", @{ $res->{errors} }));
}

sub _save {
    my ($self) = @_;
    return unless $self->_validate_tree($self->_tree);
    $self->_safe_mkyaml("", $self->_tree);
    $self->_mtime((stat $self->path)[9]);
}

__PACKAGE__->meta->make_immutable;
1;