Can store hash in a cookie?

前端 未结 3 2114
执笔经年
执笔经年 2021-02-20 10:38

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

Thanks

3条回答
  •  半阙折子戏
    2021-02-20 10:51

    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

提交回复
热议问题