Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/multitenancy/active_record/switch_db.rb

Class Method Summary collapse

Class Method Details

.connection_handler_with_multi_db_support(spec_symbol = nil) ⇒ Object Also known as: connection_handler



6
7
8
9
10
11
12
13
# File 'lib/multitenancy/active_record/switch_db.rb', line 6

def connection_handler_with_multi_db_support(spec_symbol = nil)
  return @@connection_handlers[spec_symbol] if spec_symbol
  if Thread.current[:current_db]
    @@connection_handlers[Thread.current[:current_db]] ||= ActiveRecord::ConnectionAdapters::ConnectionHandler.new
  else
    connection_handler_without_multi_db_support
  end
end

.switch_db(db, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
# File 'lib/multitenancy/active_record/switch_db.rb', line 18

def switch_db(db, &block)
  Thread.current[:current_db] = db
  unless ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[db])
  end
  yield
ensure
  ActiveRecord::Base.connection_handler.clear_active_connections! rescue puts "supressing error while clearing connections - #{$!.inspect}"
  Thread.current[:current_db] = nil
end