Can store hash in a cookie?

落花浮王杯 提交于 2020-01-01 08:43:38

问题


Anyone know if I can put a hash in the cookie? Something like this: cookies [: test] = {: top => 5,: middle => 3,: bottom => 1}

Thanks


回答1:


I woud look into serializing the hash to store it. Then deserialize it to retrieve it.

When you serialize a hash, the result will be an encoded string. This string can be decoded to get the original object back.

You could use YAML or JSON for this. Both are nicely supported in Ruby.


A YAML example

require "yaml"

cookies[:test] = YAML::dump {a: 1, b: "2", hello: "world"}
# => "---\n:a: 1\n:b: '2'\n:hello: world\n"

YAML::load cookies[:test]
# => {a: 1, b: 2, c: "world"}

A JSON example

require "json"

cookies[:test] = JSON.generate {a: 1, b: "2", hello: "world"}
# => '{"a":1,"b":"2","hello":"world"}'

JSON.parse cookies[:test]
# => {"a"=>1, "b"=>"2", "hello"=>"world"}

Note: when using JSON.parse, the resulting object will have string-based keys




回答2:


With Rails 4.1 I had to use the parentheses like this. Without that it gave an error.

cookies[:test] = JSON.generate({a: 1, b: "2", hello: "world"})



回答3:


There are a number of ways which it is possible (i.e. storing a string and evaling that value, SCARY!). This is a simple way.

cookies[:test_top]    = 5
cookies[:test_middle] = 3
cookies[:test_bottom] = 1

You can also convert to JSON and then parse it when loading the cookie.

Newer versions of Rails include automatically serialization using the session object.



来源:https://stackoverflow.com/questions/20056297/can-store-hash-in-a-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!