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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With