April 13, 2006
Older: Thorough deployment tutorial for Rails apps at TextDrive
Newer: Want railstips.org?
First reader tip: storing hashes in cookies
[Alex Griffioen](http://www.oscaralexander.com/) 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!
3 Comments
Feb 20, 2007
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.
Feb 20, 2007
@Mike – Agreed. This post was up before I was running the site.
Apr 20, 2013
In rails 3 it’s much more secure:
cookies.signed[:user] = {:name => ‘Alex’, :age => 26}.inspect
eval(cookies.signed[:user])
Thoughts? Do Tell...