Guest User

Untitled

a guest
May 22nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. package DBIx::Factory;
  2.  
  3. use Moose;
  4. use namespace::autoclean;
  5. use Scalar::Util qw/ blessed /;
  6. use Config::Any;
  7. use File::Spec;
  8. use DBI;
  9.  
  10. our $VERSION = "0.09";
  11.  
  12. has "config_base" => (
  13. is => "ro",
  14. isa => "Str",
  15. required => 1,
  16. default => sub { defined $ENV{DBIF_BASE} ? $ENV{DBIF_BASE} : q{} },
  17. );
  18.  
  19. has "config_file" => (
  20. is => "rw",
  21. isa => "Str",
  22. required => 1,
  23. default => q{},
  24. );
  25.  
  26. around BUILDARGS => sub {
  27. my ($next_method, $class, @args) = @_;
  28.  
  29. $class->$next_method(
  30. _isa_str(@args) ? ( config_base => $args[0] ) : @args
  31. );
  32. };
  33.  
  34. sub get_dbh {
  35. my ($class_or_self, @args) = @_;
  36. my $self;
  37.  
  38. if ( blessed $class_or_self ) {
  39. $self = $class_or_self;
  40. $self->config_file( $args[0] ) if _isa_str(@args);
  41. }
  42. else {
  43. $self = $class_or_self->new(
  44. _isa_str(@args) ? ( config_file => $args[0] ) :
  45. _has_odd_elm(@args) ? ( @args, undef ) : @args
  46. );
  47. }
  48.  
  49. $self->_get_dbh(
  50. _is_empty($self->config_file) ?
  51. ( ref $args[0] ? $args[0] : [@args] ) : $self->_get_config
  52. );
  53. }
  54.  
  55. sub _get_config {
  56. my $self = shift;
  57.  
  58. my ($file, $dir) = ($self->config_file, $self->config_base);
  59. my $path
  60. = ( _is_abs_path($file) or _is_empty($dir) ) ? $file :
  61. join "/", $dir, $file ;
  62.  
  63. Config::Any->load_files(
  64. { files => [$path], use_ext => 1, flatten_to_hash => 1 }
  65. )->{$path}
  66. or confess "failed to read config file: $path\n";
  67. }
  68.  
  69. sub _get_dbh {
  70. my ($self, $args) = @_;
  71.  
  72. DBI->connect(
  73. _isa_hashref($args) ? @$args{qw/ dsn userid passwd attr /} : @$args
  74. );
  75. }
  76.  
  77. sub _isa_str { @_ == 1 and not ref $_[0] }
  78.  
  79. sub _isa_hashref { ref $_[0] eq "HASH" }
  80.  
  81. sub _is_abs_path { File::Spec->file_name_is_absolute($_[0]) }
  82.  
  83. sub _is_empty { $_[0] eq q{} }
  84.  
  85. sub _has_odd_elm { @_ % 2 }
  86.  
  87. __PACKAGE__->meta->make_immutable;
  88.  
  89. 1; # End of DBIx::Factory
  90.  
  91. __END__
Add Comment
Please, Sign In to add comment