开发者

Rails save object to cookie

开发者 https://www.devze.com 2022-12-19 06:37 出处:网络
How can I serialize an array or an object and then save it into a cookie? cookies[:mydata] = serialize({

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

cookies[:mydata] = serialize({
  :key1 => 'tralala',
  :key2 => 开发者_JAVA百科'hahaha'
})

Thx!


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])
0

精彩评论

暂无评论...
验证码 换一张
取 消