Data-Context

 view release on metacpan or  search on metacpan

lib/Data/Context.pm  view on Meta::CPAN

    isa        => 'Object',
    builder    => '_log',
    lazy_build => 1,
);
has debug => (
    is         => 'rw',
    isa        => 'Int',
    builder    => '_debug',
    trigger    => \&_debug_set,
    lazy_build => 1,
);
has instance_class => (
    is       => 'rw',
    isa      => 'Str',
    default  => 'Data::Context::Instance',
);
has instance_cache => (
    is       => 'rw',
    isa      => 'HashRef[Data::Context::Instance]',
    default  => sub {{}},
    init_arg => undef,
);
has finder => (
    is       => 'rw',
    isa      => ' Data::Context::Finder',
    required => 1,
);

around BUILDARGS => sub {
    my ($orig, $class, @args) = @_;
    my $args
        = !@args     ? {}
        : @args == 1 ? $args[0]
        :              {@args};

    if ( !$args->{finder} ) {
        $args->{finder} = Data::Context::Finder::File->new(
            map { $_ => $args->{$_} }
            grep { $_ eq 'path' || /^file_/xms }
            keys %{ $args }
        );
    }

    return $class->$orig($args);
};

sub get {
    my ( $self, $path, $vars ) = @_;

    my $dci = $self->get_instance($path);

    return $dci->get_data($vars);
}

sub get_instance {
    my ( $self, $path ) = @_;

    # TODO add some cache controls here or in ::Instance::init();
    return $self->instance_cache->{$path} if $self->instance_cache->{$path};

    my @path  = split m{/+}xms, $path;
    shift @path         if !defined $path[0] || $path[0] eq '';
    push @path, 'index' if $path =~ m{/$}xms;

    my $count = 1;
    my $loader;

    # find the most appropriate file
    PATH:
    while ( @path ) {
        $loader = $self->finder->find(@path);

        last if $loader;
        last if !$self->fallback || ( $self->fallback_depth && $count++ >= $self->fallback_depth );

        pop @path;
    }

    confess "Could not find a data context config file for '$path'\n" if ! $loader;

    my $instance_class = $self->instance_class;
    return $self->instance_cache->{$path} = $instance_class->new(
        path   => $path,
        loader => $loader,
        dc     => $self,
    );
}

sub _log {
    my $self = shift;
    require Data::Context::Log;
    return Data::Context::Log->new( level => $self->debug );
}
sub _debug { return 3 }
sub _debug_set {
    my ($self, $new_debug ) = @_;
    if ( ref $self->log eq 'Data::Context::Log' ) {
        $self->log->level( $new_debug );
    }
    return $new_debug;
}

__PACKAGE__->meta->make_immutable;

1;

__END__

=head1 NAME

Data::Context - Configuration data with context

=head1 VERSION

This documentation refers to Data::Context version 0.3.

=head1 SYNOPSIS

   use Data::Context;

   # create a new Data::Context variable



( run in 1.331 second using v1.01-cache-2.11-cpan-71847e10f99 )