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!

  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!

Posted by bturner in Core

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

  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.

Thoughts? Do Tell...


(textile enabled)

About

Rails Tips is run by John Nunemaker, a web developer/programmer who has fallen deeply in love with Ruby.

Syndication

RailsTips Articles - An assortment of news and howto's related to ruby and rails.

Rails Quick Tips - These are cool Rails related links that I find. Typically, less than 5 a day.

Search