Skip to content

Commit

Permalink
Add fallback mode for development mode and similar.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Staubo committed May 20, 2011
1 parent fbdb784 commit 1511eac
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
17 changes: 17 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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
=====

Expand Down
2 changes: 1 addition & 1 deletion lib/multidb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 11 additions & 3 deletions lib/multidb/balancer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,31 @@ 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))
@candidates[name] ||= []
@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]
end
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
Expand Down

0 comments on commit 1511eac

Please sign in to comment.