Mojolicious DBIx-Class Plugin
package Mojolicious::Plugin::Dbic;
use Mojo::Base 'Mojolicious::Plugin';
use DBIx::Class;
use DBIx::Class::Schema::Loader;
DBIx::Class::Schema::Loader->naming('v7');
use constant DEBUG => $ENV{MOJO_CONFIG_DEBUG} || 0;
my $schemas = {};
# quote pending ...
sub register {
my ($self, $app, $cfg) = @_;
keys %$cfg or die "No schemas are configured";
foreach my $name (keys %$cfg) {
if (not defined $name) {
($name) = keys %$cfg or die "No schemas are configured";
}
return $schemas->{$name} if $schemas->{$name};
my $options = $cfg->{$name} or die "The schema $name is not configured";
my @conn_info = $options->{connect_info}
? @{$options->{connect_info}}
: @$options{qw(dsn user pass options)};
#if ($schemas->{$name}) {
# my $schema_class = $name;
# $schema_class =~ s/-/::/g;
# eval "use $schema_class";
# if ( my $err = $@ ) {
# die "error while loading $schema_class : $err";
# }
# $schemas->{$name} = $schema_class->connect(@conn_info)
#} else {
my $schema_class = $name;
$schema_class =~ s/-/::/g;
eval "use $schema_class";
if ($@) {
$schemas->{$name} = DBIx::Class::Schema::Loader->connect(@conn_info);
}
else {
$schemas->{$name} = $schema_class->connect(@conn_info);
}
#}
}
# Add "schema" helper
$app->helper(
schema => sub {
my $self = shift;
my $schema_name = shift;
return $schemas->{$schema_name} if $schema_name;
return (values(%$schemas))[0];
}
);
return (values(%$schemas))[0];
}
1;
=pod
$self->schema({ MyApp::DB => { dsn => 'dbi:mysql:foo', user => 'root', pass => '****' } });
=cut