Created
September 14, 2012 18:30
-
-
Save bernerdschaefer/3723781 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' | |
module Rack | |
module Mongoid | |
module Middleware | |
class Sessions | |
def initialize(app) | |
@app = app | |
@sessions = Queue.new | |
end | |
def call(env) | |
session = checkout_session | |
Mongoid::Threaded.sessions[:default] = session | |
@app.call(env) | |
ensure | |
release_session session | |
end | |
def checkout_session | |
@sessions.pop(true) | |
rescue ThreadError | |
Mongoid::Sessions::Factory.default | |
end | |
def release_session(session) | |
@sessions.push session | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will this work with Rails HTTP Streaming? It seems that release_session will be called in call() before the response body has finished streaming. This can cause problems if a template has yet to be rendered that will require database access.