Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package DBIx::Factory;
- use Moose;
- use namespace::autoclean;
- use Scalar::Util qw/ blessed /;
- use Config::Any;
- use File::Spec;
- use DBI;
- our $VERSION = "0.09";
- has "config_base" => (
- is => "ro",
- isa => "Str",
- required => 1,
- default => sub { defined $ENV{DBIF_BASE} ? $ENV{DBIF_BASE} : q{} },
- );
- has "config_file" => (
- is => "rw",
- isa => "Str",
- required => 1,
- default => q{},
- );
- around BUILDARGS => sub {
- my ($next_method, $class, @args) = @_;
- $class->$next_method(
- _isa_str(@args) ? ( config_base => $args[0] ) : @args
- );
- };
- sub get_dbh {
- my ($class_or_self, @args) = @_;
- my $self;
- if ( blessed $class_or_self ) {
- $self = $class_or_self;
- $self->config_file( $args[0] ) if _isa_str(@args);
- }
- else {
- $self = $class_or_self->new(
- _isa_str(@args) ? ( config_file => $args[0] ) :
- _has_odd_elm(@args) ? ( @args, undef ) : @args
- );
- }
- $self->_get_dbh(
- _is_empty($self->config_file) ?
- ( ref $args[0] ? $args[0] : [@args] ) : $self->_get_config
- );
- }
- sub _get_config {
- my $self = shift;
- my ($file, $dir) = ($self->config_file, $self->config_base);
- my $path
- = ( _is_abs_path($file) or _is_empty($dir) ) ? $file :
- join "/", $dir, $file ;
- Config::Any->load_files(
- { files => [$path], use_ext => 1, flatten_to_hash => 1 }
- )->{$path}
- or confess "failed to read config file: $path\n";
- }
- sub _get_dbh {
- my ($self, $args) = @_;
- DBI->connect(
- _isa_hashref($args) ? @$args{qw/ dsn userid passwd attr /} : @$args
- );
- }
- sub _isa_str { @_ == 1 and not ref $_[0] }
- sub _isa_hashref { ref $_[0] eq "HASH" }
- sub _is_abs_path { File::Spec->file_name_is_absolute($_[0]) }
- sub _is_empty { $_[0] eq q{} }
- sub _has_odd_elm { @_ % 2 }
- __PACKAGE__->meta->make_immutable;
- 1; # End of DBIx::Factory
- __END__
Add Comment
Please, Sign In to add comment