Module: ActiveRecord::ConnectionHandling

Defined in:
lib/ar_shard/active_record.rb

Instance Method Summary collapse

Instance Method Details

#connected_shards(shards: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ar_shard/active_record.rb', line 19

def connected_shards(shards: nil)
  @connected_shards ||= begin
    config_data = parse_config(shards)
    @@klass_name = self.name
    connections = {}

    shard_model.add_shared_override!

    config_data.each do |shard|
      key, conf = shard.flatten
      handler = lookup_connect(key.to_sym)

      connections[key.to_sym] = handler.establish_connection(conf)
    end

    connections
  end
end

#lookup_connect(handler_key) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/ar_shard/active_record.rb', line 49

def lookup_connect(handler_key)
  if defined?(connection_handlers)
    connection_handlers[handler_key] ||= ActiveRecord::ConnectionAdapters::ConnectionHandler.new
  else
    @@connection_handlers[handler_key] ||= ActiveRecord::ConnectionAdapters::ConnectionHandler.new
  end
end

#parse_config(config) ⇒ Object



38
39
40
41
42
43
# File 'lib/ar_shard/active_record.rb', line 38

def parse_config(config)
  return config.call if config.is_a?(Proc)
  return config if config.is_a?(Array)

  raise ARShard::Error.new 'Shard config should be Array or Proc'
end

#shard_modelObject



45
46
47
# File 'lib/ar_shard/active_record.rb', line 45

def shard_model
  @shard_model ||= @@klass_name.constantize
end

#with_shard(handler_key, &blk) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/ar_shard/active_record.rb', line 57

def with_shard(handler_key, &blk)
  shard_model.isolated_connection = connected_shards[handler_key].connection
  return_value = yield
  return_value.load if return_value.is_a? ActiveRecord::Relation
  return_value
ensure
  shard_model.isolated_connection = nil
end