website stat

Rails Cookies nuisances

Yesterday I've wrote a rant about a particular PHP nuisance. I recon the fact that what I pointed out is common practice in most of the UNIX shells but I don't see much use of it for an interpreted language. It may become quite terrifying finding some escaped characters between ' ' instead of " " in the middle of several hundred lines of code (Bruno Rodrigues cleverly suggested using a simple regex expression like '.*\\ to detect them). But I digress.

For the sake of fairness today I'm pointing out an annoyance on the Rails framework regarding the way it handles cookies.

At first shot it may seem that the cookies hash is a normal Hash. Inspecting it would return something like

RUBY:
  1. puts cookies.inspect #=> {"key1" => "value1", ..., "keyN" => "valueN"}

This immediately suggests that one might try accessing its entries by simply typing cookies['key1']. Well, not at all.

The cookies Hash is mangled so direct access would simply return that odious nil.

How to solve the issue then? Well, it's a not particularly efficient solution but I haven't found another workaround yet.

RUBY:
  1. # cookies hash is mangled so direct access is not possible
  2.   # use this instead
  3.   def cookie_value(key)
  4.     cookies.each do |cookie|
  5.       return cookie if cookie[0] == key
  6.     end
  7.   end


1 Response to “Rails Cookies nuisances”

  1. el raichu
    Published at March 16th, 2007 at 2:03 pm

    i think it’s HashWithIndifferentAccess

    (http://api.rubyonrails.org/classes/HashWithIndifferentAccess.html),

    and it doesn’t have the “[]” method.