Skip to content

Instantly share code, notes, and snippets.

@jackdoe
Created March 6, 2012 17:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jackdoe/1987717 to your computer and use it in GitHub Desktop.
Save jackdoe/1987717 to your computer and use it in GitHub Desktop.
mongoid stored rack session Rack::Session::RackAndMongo
# inspired by https://github.com/biilmann/mongo_sessions
require 'rack/session/abstract/id'
class Session
include Mongoid::Document
field :sid
field :data
field :ts, type: Integer
index :sid, unique: true #dont forget Session.create_indexes
def Session.find_by_sid(sid)
Session.first(conditions: {sid: sid})
end
end
module RackAndMongoAreAwesome
def destroy(env)
if sid = current_session_id(env)
s = Session.find_by_sid(sid)
s.destroy if s
end
end
private
def get_session(env, sid)
sid ||= generate_sid
s = Session.find_by_sid(sid)
[sid, s ? unpack(s.data) : {}]
end
def set_session(env, sid, session_data, options = {})
sid ||= generate_sid
s = Session.find_or_create_by(sid: sid)
s.ts = Time.now.to_i
s.data = pack(session_data)
s.save
sid
end
def pack(data)
[Marshal.dump(data)].pack("m*")
end
def unpack(packed)
return nil unless packed
Marshal.load(packed.unpack("m*").first)
end
end
module Rack
module Session
class RackAndMongo < Rack::Session::Abstract::ID
include RackAndMongoAreAwesome
end
end
end
__END__
#app.rb:
Mongoid.configure { |config| config.master = Mongo::Connection.new.db("ultra-awesome-site") }
#config.ru:
require './app.rb' #sinatra
require './rack-and-mongo.rb'
use Rack::Session::RackAndMongo, key: 'rack.session', domain: '.example.com', path: '/', secret: 'change_me',expire_after: 2592000
run App
#thin:
thin start -s1 --socket /tmp/thin.sock
#nginx.conf:
http {
...
upstream backend {
server unix:/tmp/thin.0.sock;
}
...
location / {
proxy_set_header Host $host;
proxy_pass http://backend;
}
}
#############
# or using int inside sinatra::base
require './rack-and-mongo.rb'
class App < Sinatra::Base
use Rack::Session::RackAndMongo, key: 'rack.session', domain: '.example.com', path: '/', secret: 'change_me',expire_after: 2592000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment