Skip to content

Instantly share code, notes, and snippets.

@bernerdschaefer
Created September 14, 2012 18:30
Show Gist options
  • Save bernerdschaefer/3723781 to your computer and use it in GitHub Desktop.
Save bernerdschaefer/3723781 to your computer and use it in GitHub Desktop.
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
@tolsen
Copy link

tolsen commented Sep 14, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment