Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add fallback mode for development mode and similar.

  • Loading branch information...
commit 1511eac06d5025315607b2e96c74ad14a3fcb7f4 1 parent fbdb784
Alexander Staubo authored
Showing with 29 additions and 4 deletions.
  1. +17 −0 README.markdown
  2. +1 −1  lib/multidb.rb
  3. +11 −3 lib/multidb/balancer.rb
View
17 README.markdown
@@ -119,6 +119,23 @@ Note that the symbol `:default` will (unless you override it) refer to the defau
top-level ActiveRecord configuration.
+Development mode
+================
+
+In development you will typically want `Multidb.use(:slave)` to still work, but you
+probably don't want to run multiple databases on your development box. To make `use`
+silently fall back to using the default connection, simply set `fallback: true` in
+`database.yml`:
+
+ production:
+ adapter: postgresql
+ database: myapp_production
+ username: ohoh
+ password: mymy
+ host: db1
+ multidb:
+ fallback: true
+
Legal
=====
View
2  lib/multidb.rb
@@ -11,8 +11,8 @@ def install!
ActiveRecord::Base.class_eval do
include Multidb::ModelExtensions
end
- @balancer = Balancer.new(@configuration)
end
+ @balancer = Balancer.new(@configuration)
end
attr_reader :balancer
View
14 lib/multidb/balancer.rb
@@ -30,7 +30,7 @@ class Balancer
def initialize(configuration)
@candidates = {}.with_indifferent_access
@configuration = configuration
- @configuration.raw_configuration[:databases].each_pair do |name, config|
+ (@configuration.raw_configuration[:databases] || {}).each_pair do |name, config|
configs = config.is_a?(Array) ? config : [config]
configs.each do |config|
candidate = Candidate.new(@configuration.default_adapter.merge(config))
@@ -38,6 +38,13 @@ def initialize(configuration)
@candidates[name].push(candidate)
end
end
+ if @configuration.raw_configuration.include?(:fallback)
+ @fallback = @configuration.raw_configuration[:fallback]
+ elsif defined?(Rails)
+ @fallback = %w(development test).include?(Rails.env)
+ else
+ @fallback = false
+ end
@default_candidate = Candidate.new(@configuration.default_pool)
unless @candidates.include?(:default)
@candidates[:default] = [@default_candidate]
@@ -45,8 +52,9 @@ def initialize(configuration)
end
def get(name, &block)
- candidates = @candidates[name] || []
- raise ArgumentError, "No such database connection '#{name}'" if candidates.blank?
+ candidates = @candidates[name]
+ candidates ||= @fallback ? @candidates[:default] : []
+ raise ArgumentError, "No such database connection '#{name}'" if candidates.empty?
candidate = candidates.respond_to?(:sample) ?
candidates.sample : candidates[rand(candidates.length)]
block_given? ? yield(candidate) : candidate
Please sign in to comment.
Something went wrong with that request. Please try again.