mirror of
https://github.com/mperham/connection_pool
synced 2023-03-27 23:22:21 -04:00
Do pass-through via a specialized class.
This commit is contained in:
parent
2eac7dcaa6
commit
8ec4b4e7c5
2 changed files with 19 additions and 10 deletions
|
@ -24,11 +24,15 @@ require 'timed_queue'
|
|||
# - :size - number of connections to pool, defaults to 5
|
||||
# - :timeout - amount of time to wait for a connection if none currently available, defaults to 5 seconds
|
||||
#
|
||||
class ConnectionPool < BasicObject
|
||||
class ConnectionPool
|
||||
DEFAULTS = { :size => 5, :timeout => 5 }
|
||||
|
||||
def self.wrap(options, &block)
|
||||
Wrapper.new(options, &block)
|
||||
end
|
||||
|
||||
def initialize(options={}, &block)
|
||||
::Kernel.raise ::ArgumentError, 'Connection pool requires a block' unless block
|
||||
raise ArgumentError, 'Connection pool requires a block' unless block
|
||||
|
||||
@available = ::TimedQueue.new
|
||||
@oid = @available.object_id
|
||||
|
@ -45,12 +49,6 @@ class ConnectionPool < BasicObject
|
|||
end
|
||||
alias_method :with_connection, :with
|
||||
|
||||
def method_missing(name, *args, &block)
|
||||
checkout.send(name, *args, &block)
|
||||
ensure
|
||||
checkin
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def checkout
|
||||
|
@ -67,4 +65,15 @@ class ConnectionPool < BasicObject
|
|||
nil
|
||||
end
|
||||
|
||||
class Wrapper < BasicObject
|
||||
def initialize(options = {}, &block)
|
||||
@pool = ::ConnectionPool.new(options, &block)
|
||||
end
|
||||
|
||||
def method_missing(name, *args, &block)
|
||||
@pool.with do |connection|
|
||||
connection.send(name, *args, &block)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
@ -50,7 +50,7 @@ class TestConnectionPool < MiniTest::Unit::TestCase
|
|||
end
|
||||
sleep 0.05
|
||||
assert_raises Timeout::Error do
|
||||
pool.do_something
|
||||
pool.with { |net| net.do_something }
|
||||
end
|
||||
|
||||
sleep 0.05
|
||||
|
@ -60,7 +60,7 @@ class TestConnectionPool < MiniTest::Unit::TestCase
|
|||
end
|
||||
|
||||
def test_passthru
|
||||
pool = ConnectionPool.new(:timeout => 0.1, :size => 1) { NetworkConnection.new }
|
||||
pool = ConnectionPool.wrap(:timeout => 0.1, :size => 1) { NetworkConnection.new }
|
||||
assert_equal 1, pool.do_something
|
||||
assert_equal 2, pool.do_something
|
||||
assert_equal 5, pool.do_something_with_block { 3 }
|
||||
|
|
Loading…
Reference in a new issue