Created
March 9, 2011 22:11
-
-
Save anonymous/863121 to your computer and use it in GitHub Desktop.
Rails 2.3 session patched to use JSON
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
# Typically this would go in a file in /config/initializers. Note you'll also need | |
# the json gem (ideally native) and then specify this in your environment: | |
# ActiveSupport::JSON.backend = 'JSONGem' | |
# A bit of Rails magic to change the way the session is "marshalled". Essentially | |
# this bit of monkeypatching makes the MemCacheStore use JSON instead of the | |
# default Ruby marshalling in order to share data seamlessly with the node.js | |
# portion of the app. | |
# TODO: combine with a persistent store or convert to redis to better preserve | |
# sessions for lurkers | |
module ActionController | |
module Session | |
class MemCacheStore < AbstractStore | |
private | |
def get_session(env, sid) | |
sid ||= generate_sid | |
begin | |
getval = @pool.get(sid, true) | |
session_strkeys = (getval && ActiveSupport::JSON.decode(getval)) || {} | |
# Convert all the keys from strings to symbols for broader compatibility | |
session = session_strkeys.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} | |
# session = session_strkeys | |
rescue MemCache::MemCacheError, Errno::ECONNREFUSED | |
session = {} | |
end | |
[sid, session] | |
end | |
def set_session(env, sid, session_data) | |
options = env['rack.session.options'] | |
expiry = options[:expire_after] || 0 | |
@pool.set(sid, session_data.to_json, expiry, true) | |
return true | |
rescue MemCache::MemCacheError, Errno::ECONNREFUSED | |
return false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment