Skip to content

Instantly share code, notes, and snippets.

@diegok
Created September 4, 2011 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegok/1192781 to your computer and use it in GitHub Desktop.
Save diegok/1192781 to your computer and use it in GitHub Desktop.
putting some code together for a mojolicious DBIC plugin
package Mojolicious::Plugin::DBIC;
use Mojo::Base 'Mojolicious::Plugin';
our $VERSION = '0.01';
my $schemas = {};
sub register {
my ($self, $app, $cfg) = @_;
Mojo::Log->debug("Initializing DBIC plugin");
keys %$cfg or die "No schemas are configured";
for my $name (keys %$cfg) {
return $schemas->{$name} if $schemas->{$name};
my $options = $cfg->{$name} or die "The schema $name is not configured";
my @conn_info;
if ( ref $options eq 'ARRAY' ) {
@conn_info = @{$options};
}
else {
@conn_info = $options->{connect_info}
? @{$options->{connect_info}}
: @$options{qw(dsn user pass options)};
}
my $schema_class = $name;
$schema_class =~ s/-/::/g;
eval "use $schema_class";
if ($@) {
Mojo::Log->debug("Can't use '$schema_class': $@");
Mojo::Log->debug('Loading schema dynamically');
eval {
use DBIx::Class::Schema::Loader;
DBIx::Class::Schema::Loader->naming('v7');
};
if ($@) {
Mojo::Log->error("Can't load schema dynamically. It seems you need to install DBIx::Class::Schema::Loader: $@");
die;
}
$schemas->{$name} = DBIx::Class::Schema::Loader->connect(@conn_info);
}
else {
$schemas->{$name} = $schema_class->connect(@conn_info);
}
}
$app->helper( schema => sub {
my $self = shift;
if ( my $schema_name = shift ) {
return $schemas->{$schema_name};
}
return (values(%$schemas))[0];
});
$app->helper( model => sub {
my ($self, $rs_name) = @_;
if ( $rs_name =~ /^ (.+) \. ([^\.]+) $/x ) {
return $self->schema($1)->resultset($2);
}
return $self->schema->resultset($rs_name);
});
return (values(%$schemas))[0];
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment