A rails gem that brings together everything needed to enable cookieless sessions in rails.
Let’s say you’re developing a mobile phone site and cookie-based sessions just don’t work for a significant segment of your user base. There are various bits of code scattered around–and at least one older plugin–for dealing with this. However, the plugin does not seem to work on recent versions of Rails and gathering the scattered code examples requires a good deal of monkey patching. That’s where this gem comes in: all the monkeys pre-patched for you.
gem install tatyree-cookieless_sessions --source http://gems.github.com
First, you need to set up an alternative session store in environment.rb
config.action_controller.session_store = :mem_cache_store
We’ve only ever used it with the mem_cache_store, but there’s no reason that it shouldn’t work with any other server-side store.
Next, require it in environment.rb after the Rails::Initializer block:
require 'cookieless_sessions'
Lastly, add a before_filter to the ApplicationController to check to see if cookies are enabled:
class ApplicationController < ActionController::Base ... before_filter :check_cookies ... protected ... def check_cookies cookies[:_sessions] ||= { :value => 'true', :expires => 30.seconds.from_now } unless session[:cookies_off] if cookies.blank? logger.info "** Cookies appear to be disabled on this session." session[:cookies_off] = true end end
I suggest that, once a session has been flagged as cookieless, it should not be changed back (i.e. else; session[:cookies_off] = false; end;
). If it is possible for cookies_off to change on-the-fly, then the current session will be lost if cookie handling flip-flops.
You can customize this method as you see fit. Please note, however, that the gem depends on the :cookies_off session key and is checking for an explicit boolean true.
This code is currently running on Rails 2.1.0, 2.1.2 and 2.2.2 based sites.
There aren’t very many. Variations of this have been running in production on several of our apps for months now.
The main thing to watch out for is phones that can’t handle GET and POST variables in the same request. Happily, they are becoming rare (and, if I’m honest, using both methods in one request is pretty flakey).
The main symptom is a controller method throwing exceptions because the only parameter it receives is the session_id: The phone sees the query string on the form action and discards any other parameters. So far, I’ve tried incorporating the session_id as a hidden variable in the form. This works fine for passing the parameter, but getting the session handling code to pick it up, and selectively excluding the query parameter from the form action url has proven very difficult.
MIT