Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails save object to cookie

How can I serialize an array or an object and then save it into a cookie?

cookies[:mydata] = serialize({
  :key1 => 'tralala',
  :key2 => 'hahaha'
})

Thx!

like image 252
xpepermint Avatar asked Feb 01 '10 12:02

xpepermint


1 Answers

The recent rails vulnerabilities (especially the one involving rack), made me question how safe was the Marshal.load approach I initially recommended.

Please don't use is, as it's dangerous and may potentially allow remote code execution. I've removed it from this answer.

While not as flexible the following should work as well:

Initial object:

my_object = {:k1 => 'v1', :k2 => 'v2'}

Saving:

cookies[:my_data] = { 
  :value => my_object.to_json, 
  :expires => 4.years.from_now
}

Reading:

my_object = JSON.parse(cookies[:my_data])
like image 111
vise Avatar answered Oct 27 '22 15:10

vise