Class: ShardHandler::Handler Private

Inherits:
Object
  • Object
show all
Defined in:
lib/shard_handler/handler.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Handles which ConnectionHandler instance should be used based on the shard name that is set for the Thread. Each Model class has its own Handler.

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(klass, configs) ⇒ Handler

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Handler.

Parameters:

  • klass (ActiveRecord::Base)

    model class

  • configs (Hash)

    a hash with database connection settings



11
12
13
14
15
# File 'lib/shard_handler/handler.rb', line 11

def initialize(klass, configs)
  @klass = klass
  @configs = configs
  @cache = {}
end

Instance Method Details

#connection_handler_for(name) ⇒ ActiveRecord::ConnectionAdapters::ConnectionHandler

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the appropriate ConnectionHandler instance for the given shard name.

Parameters:

  • name (Symbol, String)

    shard name

Returns:

  • (ActiveRecord::ConnectionAdapters::ConnectionHandler)


37
38
39
40
41
# File 'lib/shard_handler/handler.rb', line 37

def connection_handler_for(name)
  @cache.fetch(name.to_sym) do
    fail UnknownShardError, "#{name.inspect} is not a valid shard name"
  end
end

#disconnect_allObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Disconnects from all shards.



44
45
46
# File 'lib/shard_handler/handler.rb', line 44

def disconnect_all
  @cache.values.map(&:clear_all_connections!)
end

#setupObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a ConnectionHandler instance for each configured shard and puts it on cache to be used later by #connection_handler_for.



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/shard_handler/handler.rb', line 19

def setup
  resolver = ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new(@configs)

  @configs.each do |name, _|
    name = name.to_sym

    connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
    connection_handler.establish_connection(@klass, resolver.spec(name))

    @cache[name] = connection_handler
  end
end