Created
November 16, 2012 00:56
-
-
Save TristinDavis/4082910 to your computer and use it in GitHub Desktop.
Mojolicious DBIx-Class Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment