Deleting Session and Cookie entries

I’ve had a problem with clearing a users session and cookie information if they failed log on. In the past I’ve simply used:

  def clear_session
    session[:user_id] = ""
    session[:user_hash] = ""
    cookies[:user_hash] = ""
  end

But this often fails to clear the setting when I tested in Firefox. I tried to find an option to delete a session or cookie entry but could not get either session.delete(:name) or session[:name].delete (which I found references to) to work.

So I’ve used a pragmatic approach to the problem. This works:

  def clear_session
    session[:user_id] = "dead"
    session[:user_hash] = "dead"
    cookies[:user_hash] = { :value => "dead", :expires => 1.minute.ago }
  end

It’s not pretty, but it works. It seems that at least for Firefox, you need to pass something to the browser cookie (session after all is a glorified cookie) to over-write it. Passing it nothing can leave the old entry there.

Of course you need to pass it something that your application will find invalid as an entry for that value. For example User.find(’dead’) will return nil.

This entry was posted in Ruby. Bookmark the permalink.