Reputation: 36243
How can I serialize an array or an object and then save it into a cookie?
cookies[:mydata] = serialize({
:key1 => 'tralala',
:key2 => 'hahaha'
})
Thx!
Upvotes: 5
Views: 4731
Reputation: 13383
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])
Upvotes: 15