Class: WithConnection::RangedConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/with_connection/ranged_connection_pool.rb

Defined Under Namespace

Classes: BasicRange, Item

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ranges_and_pools, default_pool, key_algo) ⇒ RangedConnectionPool

Returns a new instance of RangedConnectionPool.



5
6
7
8
9
# File 'lib/with_connection/ranged_connection_pool.rb', line 5

def initialize(ranges_and_pools, default_pool, key_algo)
  @list = ranges_and_pools.map { |range, pool| Item.new(range, pool) }
  @default_pool = default_pool
  @key_algo = key_algo
end

Instance Attribute Details

#default_poolObject (readonly)

Returns the value of attribute default_pool.



3
4
5
# File 'lib/with_connection/ranged_connection_pool.rb', line 3

def default_pool
  @default_pool
end

#key_algoObject (readonly)

Returns the value of attribute key_algo.



3
4
5
# File 'lib/with_connection/ranged_connection_pool.rb', line 3

def key_algo
  @key_algo
end

#listObject (readonly)

Returns the value of attribute list.



3
4
5
# File 'lib/with_connection/ranged_connection_pool.rb', line 3

def list
  @list
end

Instance Method Details

#connectionObject



16
17
18
19
# File 'lib/with_connection/ranged_connection_pool.rb', line 16

def connection
  local_current[:pool] ||= @default_pool
  local_current[:pool].connection
end

#create_all_connectionsObject



32
33
34
35
# File 'lib/with_connection/ranged_connection_pool.rb', line 32

def create_all_connections
  @default_pool.create_all_connections
  @list.each { |item| item.pool.create_all_connections }
end

#local_currentObject



28
29
30
# File 'lib/with_connection/ranged_connection_pool.rb', line 28

def local_current
  defined?(EM) && EM.reactor_running? ? Fiber.current : Thread.current
end

#pool_for_key(key) ⇒ Object



21
22
23
24
25
26
# File 'lib/with_connection/ranged_connection_pool.rb', line 21

def pool_for_key(key)
  key = self.key_algo.call(key) if key
  key.nil? ?
  @default_pool : 
    (@list.detect { |item| item.include?(key) } || @default_pool)
end

#with_connection(key = nil, &block) ⇒ Object



11
12
13
14
# File 'lib/with_connection/ranged_connection_pool.rb', line 11

def with_connection(key=nil, &block)
  local_current[:pool] = pool_for_key(key)
  local_current[:pool].with_connection(&block)
end