Rails Cookies nuisances
- Published February 19th, 2007 in Ruby
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
-
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.
-
# cookies hash is mangled so direct access is not possible
-
# use this instead
-
def cookie_value(key)
-
cookies.each do |cookie|
-
return cookie if cookie[0] == key
-
end
-
end




i think it’s HashWithIndifferentAccess
(http://api.rubyonrails.org/classes/HashWithIndifferentAccess.html),
and it doesn’t have the “[]” method.