How can I serialize an array or an object and then save it into a cookie?
cookies[:mydata] = serialize({
:key1 => 'tralala',
:key2 => '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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.