First reader tip: storing hashes in cookies

[Alex Griffioen]( 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!

  1. set cookie
    user = {:name => “Alex”, :age => 25}
    cookies[:user] = user.inspect
  1. get cookie
    user = eval(cookies[:user])
    user[:name] # => Alex

Hope this helps anyone :)

Thanks for the tip, Alex!


  1. 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.

  2. @Mike – Agreed. This post was up before I was running the site.

  3. In rails 3 it’s much more secure:

    cookies.signed[:user] = {:name => ‘Alex’, :age => 26}.inspect

Thoughts? Do Tell...

textile enabled, preview above, please be nice
use <pre><code class="ruby"></code></pre> for code blocks


Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.


Release your software more often with fewer problems.
Flip your features.