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!

2 Responses to “First reader tip: storing hashes in cookies”

  1. Mike Owens Says:

    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. John Nunemaker Says:

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

Leave a Reply


(textile enabled)