Nov 24, 2010

Rails's cookies

Here is some strange behaviour:

def index
cookies[:key] = "val"
puts cookies[:key]
redirect_to :second_index
end

def second_index
cookies[:key] = "newval"
puts cookies[:key]
end

## Output :
## Open index page for the first time
# nil
# val

## Open index page the second time
# newval
# val



cookies[] is to retrieve the current cookies
but cookies[]= is to assign outgoing cookies, not to re-assign the current cookies.
Actually, you can never re-assign the current cookies.

-----------------------------------------

Here is another different behaviour of using sign and string as indices:

## cookies and request.cookies are different
cookies.class #=> ActionController::CookieJar
request.cookies #=> Hash

## how to access value from cookies and request.cookies
# First set some value in cookies
cookies[:key] = "value"

cookies["key"] #=> "value"
cookies[:key] #=> "value"
# both the output are of type String

request.cookies["key"] #=> "value"
request.cookies["key"].class #=> CGI::Cookie

request.cookies[:key].empty? #=> true
request.cookies[:key].class #=> Array

Ref: http://www.quarkruby.com/2007/10/21/sessions-and-cookies-in-ruby-on-rails#scinrails