Created
March 6, 2012 17:48
-
-
Save jackdoe/1987717 to your computer and use it in GitHub Desktop.
mongoid stored rack session Rack::Session::RackAndMongo
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
# 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