Permalink
Browse files

Use ActiveRecord's with_connection when possible.

  • Loading branch information...
Alexander Staubo
Alexander Staubo committed May 19, 2011
1 parent a566e36 commit fbdb7841168d3dbda0d7aab19554e5b7ae05ea74
Showing with 16 additions and 11 deletions.
  1. +16 −11 lib/multidb/balancer.rb
View
@@ -16,8 +16,12 @@ def initialize(target)
end
end
- def connection
- @connection_pool.connection
+ def connection(&block)
+ if block_given?
+ @connection_pool.with_connection(&block)
+ else
+ @connection_pool.connection
+ end
end
end
@@ -51,18 +55,19 @@ def get(name, &block)
def use(name, &block)
result = nil
get(name) do |candidate|
- connection = candidate.connection
if block_given?
- previous_connection, Thread.current[:multidb_connection] =
- Thread.current[:multidb_connection], connection
- begin
- result = yield
- ensure
- Thread.current[:multidb_connection] = previous_connection
+ candidate.connection do |connection|
+ previous_connection, Thread.current[:multidb_connection] =
+ Thread.current[:multidb_connection], connection
+ begin
+ result = yield
+ ensure
+ Thread.current[:multidb_connection] = previous_connection
+ end
+ result
end
- result
else
- result = Thread.current[:multidb_connection] = connection
+ result = Thread.current[:multidb_connection] = candidate.connection
end
end
result

0 comments on commit fbdb784

Please sign in to comment.