Created
September 14, 2012 18:32
-
-
Save bernerdschaefer/3723793 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'queue' | |
# Simplified version of the pooling from datamapper's data_objects. | |
# https://github.com/datamapper/do/blob/master/data_objects/lib/data_objects/pooling.rb | |
class Moped::Session | |
class << self | |
alias new __new | |
end | |
@__pool_lock = Mutex.new | |
def self.new(*args) | |
(@__pools[args] ||= @__pool_lock.synchronize { Pool.new(self, args) }).reserve | |
end | |
def release | |
@__pool.release(self) | |
end | |
class Pool | |
def initialize(klass, args) | |
@klass = klass | |
@args = args | |
@pool = Queue.new | |
end | |
def release(instance) | |
@pool.push(instance) | |
end | |
def reserve | |
@pool.pop(true) | |
rescue ThreadError | |
instance = @klass.__new(*@args) | |
instance.instance_variable_set(:@__pool, self) | |
instance | |
end | |
end | |
end | |
module Rack | |
module Mongoid | |
module Middleware | |
class Sessions | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
ensure | |
Mongoid::Threaded.sessions.each do |_, session| | |
session.release | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment