module SwitchConnection::Model::ClassMethods

Public Instance Methods

switch_point_name() click to toggle source
# File lib/switch_connection/model.rb, line 87
def switch_point_name
  thread_local_switch_point_name || @global_switch_point_name
end
switch_point_proxy() click to toggle source
# File lib/switch_connection/model.rb, line 101
def switch_point_proxy
  if switch_point_name
    ProxyRepository.checkout(switch_point_name)
  elsif self == ActiveRecord::Base
    nil
  else
    superclass.switch_point_proxy
  end
end
thread_local_switch_point_name() click to toggle source
# File lib/switch_connection/model.rb, line 91
def thread_local_switch_point_name
  Thread.current[:"thread_local_#{name}_switch_point_name"]
end
transaction_with(*models, &block) click to toggle source
# File lib/switch_connection/model.rb, line 111
def transaction_with(*models, &block)
  unless can_transaction_with?(*models)
    raise Error.new("switch_point's model names must be consistent")
  end

  with_master do
    transaction(&block)
  end
end
use_switch_point(name) click to toggle source
# File lib/switch_connection/model.rb, line 74
def use_switch_point(name)
  assert_existing_switch_point!(name)
  @global_switch_point_name = name
end
with_master() { || ... } click to toggle source
# File lib/switch_connection/model.rb, line 66
def with_master(&block)
  if switch_point_proxy
    switch_point_proxy.with_master(&block)
  else
    yield
  end
end
with_slave() { || ... } click to toggle source
# File lib/switch_connection/model.rb, line 58
def with_slave(&block)
  if switch_point_proxy
    switch_point_proxy.with_slave(&block)
  else
    yield
  end
end
with_switch_point(new_switch_point_name) { || ... } click to toggle source
# File lib/switch_connection/model.rb, line 79
def with_switch_point(new_switch_point_name)
  saved_switch_point_name = thread_local_switch_point_name
  self.thread_local_switch_point_name = new_switch_point_name
  yield
ensure
  self.thread_local_switch_point_name = saved_switch_point_name
end

Private Instance Methods

assert_existing_switch_point!(name) click to toggle source
# File lib/switch_connection/model.rb, line 123
def assert_existing_switch_point!(name)
  SwitchConnection.config.fetch(name)
end
can_transaction_with?(*models) click to toggle source
# File lib/switch_connection/model.rb, line 127
def can_transaction_with?(*models)
  master_switch_points = [self, *models].map do |model|
    next unless model.switch_point_name

    SwitchConnection.config.model_name(
      model.switch_point_name,
      :master
    )
  end

  master_switch_points.uniq.size == 1
end
thread_local_switch_point_name=(name) click to toggle source
# File lib/switch_connection/model.rb, line 95
def thread_local_switch_point_name=(name)
  Thread.current[:"thread_local_#{self.name}_switch_point_name"] = name
end