Rails — cookies adds an array

Multi tool use
Rails — cookies adds an array
I store an array to cookies in someone method:
def someone
cookies[:test] = JSON.generate [@page.image, @page.title]
end
But I want to cookies[:test] can store more information as "<<" not "=",
like(will get an error):
def someone
cookies[:test] << JSON.generate [@page.image, @page.title]
end
Now, cookies[:test].inspect
is [[@page.image, @page.title], [@page.image, @page.title]]
.
How to make this?
cookies[:test].inspect
[[@page.image, @page.title], [@page.image, @page.title]]
1 Answer
1
I don't think it's possible to append directly to the cookie; it's stored as a string (which JSON.generate returns), so you need to deserialize, append, then reserialize and store:
current = JSON.parse cookies[:test]
current << [@page.image, @page.title]
cookies[:test] = JSON.generate current
Or a little more succinctly:
cookies[:test] = (JSON.parse(cookies[:test]) + [[@page.image, @page.title]]).to_json
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.