Module: SwitchConnection::Model::ClassMethods

Defined in:
lib/switch_connection/model.rb

Instance Method Summary collapse

Instance Method Details

#switch_point_nameObject



87
88
89
# File 'lib/switch_connection/model.rb', line 87

def switch_point_name
  thread_local_switch_point_name || @global_switch_point_name
end

#switch_point_proxyObject



101
102
103
104
105
106
107
108
109
# 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_nameObject



91
92
93
# 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) ⇒ Object



111
112
113
114
115
116
117
118
119
# 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) ⇒ Object



74
75
76
77
# 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(&block) ⇒ Object



66
67
68
69
70
71
72
# 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(&block) ⇒ Object



58
59
60
61
62
63
64
# 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) ⇒ Object



79
80
81
82
83
84
85
# 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