Hijacker

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