Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

Thanks

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"}
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

This doesn't work for me at all :( I get complaints about the ":" character (syntax error, unexpected ':', expecting '}') Any ideas why? I've tried both your YAML and JSON suggestions, but both complain of the same issue. – justinraczak Jun 2, 2014 at 6:17 FWIW, I did this a little differently which worked well for me. cookies[:my_cookie] = { value: ActiveSupport::JSON.encode(my_object), expires: some_time } I pulled it back out in a similar fashion with decode. Thanks for setting me on the right path, though. – justinraczak Jun 2, 2014 at 6:51

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.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.