ruby mongoid存储架会话Rack :: Session :: RackAndMongo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby mongoid存储架会话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
以上是关于ruby mongoid存储架会话Rack :: Session :: RackAndMongo的主要内容,如果未能解决你的问题,请参考以下文章
Mongoid 在 ruby 1.9.3 上失败
使用 Mongoid 和 Ruby 查询最近 30 天的日期范围?
ruby 生成ruby.rack.status_code.snip
ruby Mongoid数据库可缓存
ruby mongoid_document.rb
Ruby on Rails 是 mongodb - mongoid