Class: SwitchPoint::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/switch_point/proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Proxy

Returns a new instance of Proxy.



3
4
5
6
7
8
9
10
11
12
# File 'lib/switch_point/proxy.rb', line 3

def initialize(name)
  @models = {}
  [:readonly, :writable].each do |mode|
    model = define_model(SwitchPoint.config.model_name(name, mode))
    @models[mode] = model
    model.establish_connection(SwitchPoint.config.database_name(name, mode))
    memorize_switch_point(name, mode, model.connection)
  end
  @mode = :readonly
end

Instance Method Details

#connectionObject



49
50
51
# File 'lib/switch_point/proxy.rb', line 49

def connection
  @models[@mode].connection
end

#define_model(model_name) ⇒ Object



14
15
16
17
18
# File 'lib/switch_point/proxy.rb', line 14

def define_model(model_name)
  model = Class.new(ActiveRecord::Base)
  Proxy.const_set(model_name, model)
  model
end

#memorize_switch_point(name, mode, connection) ⇒ Object



20
21
22
23
# File 'lib/switch_point/proxy.rb', line 20

def memorize_switch_point(name, mode, connection)
  switch_point = { name: name, mode: mode }
  connection.pool.instance_variable_set(:@switch_point, switch_point)
end

#readonly!Object



25
26
27
# File 'lib/switch_point/proxy.rb', line 25

def readonly!
  @mode = :readonly
end

#with_connection(mode, &block) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/switch_point/proxy.rb', line 41

def with_connection(mode, &block)
  saved_mode = @mode
  @mode = mode
  block.call
ensure
  @mode = saved_mode
end

#with_readonly(&block) ⇒ Object



33
34
35
# File 'lib/switch_point/proxy.rb', line 33

def with_readonly(&block)
  with_connection(:readonly, &block)
end

#with_writable(&block) ⇒ Object



37
38
39
# File 'lib/switch_point/proxy.rb', line 37

def with_writable(&block)
  with_connection(:writable, &block)
end

#writable!Object



29
30
31
# File 'lib/switch_point/proxy.rb', line 29

def writable!
  @mode = :writable
end