如何构建自己的自定义会话商店类?

kha*_*anh 6 ruby session ruby-on-rails-3

默认情况下,会话存储在浏览器cookie(:cookie_store)中,但您也可以指定其中一个包含的存储(:active_record_store,:mem_cache_store或您自己的自定义类.请给我构建自定义类的方法

config.action_controller.session_store = :your_customer_class
Run Code Online (Sandbox Code Playgroud)

小智 6

MaurícioLinhares是正确的,但是,我想添加一些细节,因为我认为你需要实现哪些方法是显而易见的.

您可以从ActionDispatch :: Session :: AbstractStore继承,但它继承自Rack :: Session :: Abstract :: ID,这是查找您需要实现的方法的好地方.具体来说,从Rack :: Session :: Abstract :: ID:

# All thread safety and session retrival proceedures should occur here.
# Should return [session_id, session].
# If nil is provided as the session id, generation of a new valid id
# should occur within.

def get_session(env, sid)
  raise '#get_session not implemented.'
end

# All thread safety and session storage proceedures should occur here.
# Should return true or false dependant on whether or not the session
# was saved or not.

def set_session(env, sid, session, options)
  raise '#set_session not implemented.'
end

# All thread safety and session destroy proceedures should occur here.
# Should return a new session id or nil if options[:drop]

def destroy_session(env, sid, options)
  raise '#destroy_session not implemented'
end
Run Code Online (Sandbox Code Playgroud)

我写了一个简单的基于文件的会话存储作为实验.

  • 继承 `Rack::Session::Abstract::ID` 已被弃用。现在应该是“Rack::Session::Abstract::Persisted”。 (2认同)