Class: Backchat::ConnectionPool

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/backchat/connection_pool.rb

Constant Summary collapse

DEFAULT_SETTINGS =
{
host: 'localhost',
username: 'admin',
password: 'password',
pool_size: 5,
persistent: true }

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count = self.class.settings[:pool_size]) ⇒ ConnectionPool

Returns a new instance of ConnectionPool.



14
15
16
# File 'lib/backchat/connection_pool.rb', line 14

def initialize(count = self.class.settings[:pool_size])
  @queue = fill(SizedQueue.new(count))
end

Class Attribute Details

.settingsObject (readonly)

Returns the value of attribute settings.



43
44
45
# File 'lib/backchat/connection_pool.rb', line 43

def settings
  @settings
end

Class Method Details

.configure(settings = {}, &block) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/backchat/connection_pool.rb', line 45

def configure(settings = {}, &block)
  if block_given?
    instance_eval(&block)
  else
    @settings.merge!(settings)
  end
end

.connection(credentials = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/backchat/connection_pool.rb', line 53

def connection(credentials = {})
  connection = XMPPConnection.new(settings[:host])
  connection.connect
  if (credentials.keys & [:username, :password]).count == 2
    connection.(*credentials.values_at(:username, :password))
  end

  yield connection
ensure
  connection.disconnect
end

Instance Method Details

#add(connection) ⇒ Object



26
27
28
# File 'lib/backchat/connection_pool.rb', line 26

def add(connection)
  queue.push(connection)
end

#countObject



18
19
20
# File 'lib/backchat/connection_pool.rb', line 18

def count
  queue.length
end

#takeObject



22
23
24
# File 'lib/backchat/connection_pool.rb', line 22

def take
  queue.pop
end

#with_connectionObject



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/backchat/connection_pool.rb', line 30

def with_connection
  connection = take
  connection.connect unless connection.is_connected?
  connection.(self.class.settings[:username],
                   self.class.settings[:password],
                   "resource_#{connection.connection_id}") unless connection.is_authenticated?
  yield connection
ensure
  connection.disconnect unless self.class.settings[:persistent]
  add(connection)
end