Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created March 13, 2009 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choonkeat/78819 to your computer and use it in GitHub Desktop.
Save choonkeat/78819 to your computer and use it in GitHub Desktop.
This controller illustrates the problem of Rails sending "Set-Cookie" back to the client when cookie-store is being used -- even when session data has NOT changed
# This controller illustrates the problem of Rails sending "Set-Cookie" back to the client
# when cookie-store is being used -- even when session data has NOT changed.
class HomeController < ApplicationController
def index
%w[one two three four five six].each do |word|
session[word] = word
end
render :text => "<a href='#{url_for(:action => 'show')}'>click here</a>"
end
def reset
session.delete
redirect_to :action => 'index'
end
# 1. Click on "reload page" repeatedly.
# 2. Notice no session data is modified, but the cookie keeps changing
# 2. Whenever it changes, a "Set-Cookie" response header will be sent to browser
# 3. This is not good for caching facility like Varnish
# See next comment block for a fix
def show
render :text => "<a href='#{url_for()}'>reload page</a> | <a href='#{url_for(:action => 'reset')}'>reset</a><br />" +
CGI.escapeHTML(session.instance_variable_get('@data').inspect) + "<br />" +
CGI.escapeHTML(request.cookies.inspect)
end
end
# The Fix: use an ordered hash instead.
# 1. Uncomment the code below
# 2. Restart your server & reset the cookies
# 3. Repeated clicks on "reload page" should yield the same cookie string henceforth
#
# CGI::Session::CookieStore.class_eval do
# def restore
# @original = read_cookie
# # Commented off faulty code in action_controller/session/cookie_store.rb
# # @data = unmarshal(@original) || {}
# @data = unmarshal(@original) || ActiveSupport::OrderedHash.new
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment