Rails — cookies adds an array

Multi tool use
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.

Vv8c,OAKTb OF92,GCqRTF,Oewm,O rT9tGC8,TXfPPPFYJjJ VVj5 Vxkg2MLGmJv7njaaGVCrIMKbGo,r1yt0
AbV6C0d8Rjv OPD,py

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications