First reader tip: storing hashes in cookies
April 13th, 2006
wrote in with a tip, and I’m sorry it took so, so long to get this up on the site. Here’s Alex’s tip:
I spent about an hour and a half trying to figure out how I could store a hash in a cookie using Marshaling, etc. I eventually gave up and decided to store it as a plain ‘ol comma-separated string.
This morning I woke up and it struck me. Eureka! Inspect() and eval() are your friends!
- set cookie user = {:name => “Alex”, :age => 25} cookies[:user] = user.inspect
- get cookie user = eval(cookies[:user]) user[:name] # => Alex
Hope this helps anyone :)
Thanks for the tip, Alex!

February 20th, 2007 at 04:31 PM
I know that this post is from almost a year ago, but for people just finding it, it is a very bad idea to call eval() on a string sent to you by the browser, or any other untrusted input.
An attacker could trivially send a cookie containing malicious Ruby code which will be executed on your server.
For doing things like this, use a proper parser, for example, JSON.parse() or Syck, which does not allow arbitrary code execution.
February 20th, 2007 at 11:40 PM
@Mike – Agreed. This post was up before I was running the site.