Module: ActiveRecord::Base::Replica

Included in:
ActiveRecord::Base
Defined in:
lib/replica/base.rb

Defined Under Namespace

Classes: Proxy

Instance Method Summary collapse

Instance Method Details

#connection_pool_nameObject

Name of the connection pool. Used by ConnectionHandler to retrieve the current connection pool.



37
38
39
40
41
42
43
44
45
46
# File 'lib/replica/base.rb', line 37

def connection_pool_name # :nodoc:
  replica = current_replica_name
  if replica
    "#{name}_#{replica}"
  elsif self == ActiveRecord::Base
    name
  else
    superclass.connection_pool_name
  end
end

#with_master(&block) ⇒ Object

See with_slave



24
25
26
# File 'lib/replica/base.rb', line 24

def with_master(&block)
  with_replica(nil, &block)
end

#with_replica(replica_name, &block) ⇒ Object

Specify which database to use.

Example: database.yml

test_slave:
  adapter: mysql
  ...

Account.with_replica(:slave) { Account.count } Account.with_replica(:slave).count



59
60
61
62
63
64
65
# File 'lib/replica/base.rb', line 59

def with_replica(replica_name, &block)
  if block_given?
    with_replica_block(replica_name, &block)
  else
    Proxy.new(self, replica_name)
  end
end

#with_replica_block(replica_name, &block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/replica/base.rb', line 67

def with_replica_block(replica_name, &block)
  old_replica_name = current_replica_name
  begin
    self.current_replica_name = replica_name
  rescue ActiveRecord::AdapterNotSpecified => e
    self.current_replica_name = old_replica_name
    logger.warn("Failed to establish replica connection: #{e.message} - defaulting to master")
  end
  yield
ensure
  self.current_replica_name = old_replica_name
end

#with_slave(&block) ⇒ Object

Executes queries using the slave database. Fails over to master if no slave is found. if you want to execute a block of code on the slave you can go:

Account.with_slave do
  Account.first
end

the first account will be found on the slave DB

For one-liners you can simply do

Account.with_slave.first

this is the same as:

Account.with_replica(:slave) do
  Account.first
end


19
20
21
# File 'lib/replica/base.rb', line 19

def with_slave(&block)
  with_replica(:slave, &block)
end

#with_slave_if(condition, &block) ⇒ Object



28
29
30
# File 'lib/replica/base.rb', line 28

def with_slave_if(condition, &block)
  condition ? with_slave(&block) : with_master(&block)
end

#with_slave_unless(condition, &block) ⇒ Object



32
33
34
# File 'lib/replica/base.rb', line 32

def with_slave_unless(condition, &block)
  with_slave_if(!condition, &block)
end