Created
March 4, 2013 23:50
-
-
Save mtgrosser/5086733 to your computer and use it in GitHub Desktop.
Fixed RedisSessionStore for Rails 3.2
This file contains hidden or 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
require 'redis' | |
# Redis session storage for Rails, and for Rails only. Derived from | |
# the MemCacheStore code, simply dropping in Redis instead. | |
# | |
# Options: | |
# :key => Same as with the other cookie stores, key name | |
# :host => Redis host name, default is localhost | |
# :port => Redis port, default is 6379 | |
# :db => Database number, defaults to 0. Useful to separate your session storage from other data | |
# :key_prefix => Prefix for keys used in Redis, e.g. myapp-. Useful to separate session storage keys visibly from others | |
# :expire_after => A number in seconds to set the timeout interval for the session. Will map directly to expiry in Redis | |
class RedisSessionStore < ActionDispatch::Session::AbstractStore | |
def initialize(app, options = {}) | |
super | |
@redis = Redis.new(options) | |
end | |
def get_session(env, sid) | |
sid ||= generate_sid | |
begin | |
data = @redis.get(prefixed(sid)) | |
session = data.nil? ? {} : Marshal.load(data) | |
rescue Errno::ECONNREFUSED | |
session = {} | |
end | |
[sid, session] | |
end | |
def set_session(env, sid, session, options) | |
expiry = options[:expire_after] || nil | |
if session | |
if expiry | |
@redis.setex(prefixed(sid), expiry, Marshal.dump(session)) | |
else | |
@redis.set(prefixed(sid), Marshal.dump(session)) | |
end | |
else | |
@redis.del(prefixed(sid)) | |
end | |
sid | |
rescue Errno::ECONNREFUSED | |
return false | |
end | |
# Remove a session from the cache. | |
def destroy_session(env, sid, options) | |
@redis.del(prefixed(sid)) | |
generate_sid | |
end | |
private | |
def prefixed(sid) | |
"#{@default_options[:key_prefix]}#{sid}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment