Plugin to use one application across multiple client databases, note this is a little premature for public consumption
Ruby
Failed to load latest commit information.
example Test a host with no dbs Apr 17, 2013
lib Automatically fix bad connections Feb 8, 2016
spec
tasks Initial commit Aug 11, 2009
.gitignore Automatically fix bad connections Feb 8, 2016
CHANGELOG.md
Gemfile Remove unused shitty files and debugger Apr 16, 2013
Gemfile.lock
Guardfile Update specs/deps for Rails 3 Jun 18, 2014
MIT-LICENSE Initial commit Aug 11, 2009
README.rdoc Readd do_hijacking method Oct 3, 2013
Rakefile Fix wrong path Jun 19, 2014
circle.yml
dbhijacker.gemspec bump version Feb 8, 2016
example_root_schema.rb Set a good example using unique index Jun 18, 2014

README.rdoc

Hijacker

I don't recommend you use this gem. It is not production quality.

Notes for adding thread safety: github.com/discourse/discourse/blob/691377b5af72ea0f3223223cfb623b991c96cbb8/vendor/gems/rails_multisite/lib/rails_multisite/connection_management.rb

One application, multiple client databases. Although customizable, by default uses a combination of database and regular expression matching against the host domain to figure out which database to connect to.

Example

class ApplicationController < ActionController::Base
  hijack_connection({
    # First thing it does is look for static routes. If this option
    # exists and returns a string, it'll use that as the database
    :static_routes => Proc.new {
      case RAILS_ENV
      when "development" then "site_development"
      when "test" then "site_test"
      end
    },
    # If it can't find the host in root.databases, it'll try pattern matching.
    # Grabs $1 after a successful match.
    :domain_patterns => [
      /^(.+)\.domain\.com/, /^.+\.(.+)\..+/, /^(.+)\..+/
    ],
    :after_hijack => Proc.new {
      # Classes using acts_as_nested_set load the table info when preloading code in production.
      # This is wrong 'cause at that point AR is connected to the root database.
      Category.reset_column_information
    }
  })
end

For copy/pasters, a shorter version:

hijack_connection({
  :static_routes => Proc.new { "site_#{Rails.env}" if !(Rails.env == "production") },
  :domain_patterns => [/^(.+)\.site\.com/, /^.+\.(.+)\..+/, /^(.+)\..+/],
  :after_hijack => Proc.new { Category.reset_column_information }
})

Configuration

Your database.yml needs a “root” connection like so:

...

root: &root
  database: root
  <<: *defaults

production:
  <<: *root

...

Other parts of database.yml will remain the same (development, test) but production apps will initially start up on this root database, then hijack when the first connection comes in.

Running tests

To run the tests, just invoke RSpec:

rspec spec

Copyright © 2012 Michael Xavier, Donald Plummer, Woody Peterson, released under the MIT license