Petros Kyriakou
Petros Kyriakou

Reputation: 5343

How to store more than one values, in same cookie - Rails

So i want to store a comment_id:value pair and a comment_user:value pair

So far i do this

cookies.signed[:comment_author] = { value: @comment.id, expires: 2.hour.from_now }

Basically i am trying to figure out how to store more than one value to same cookie so to avoid creating multiple cookies for same user. Is that possible?

Question 2: how can i dynamically append to that cookie if any values exist?

Upvotes: 1

Views: 524

Answers (1)

Dmitry Sokurenko
Dmitry Sokurenko

Reputation: 6122

The only way to do it using one cookie is to serialize the data into some textual format like YAML or JSON.

Example:

cookies.signed[:comment_data] = { value: {comment_id: 1, comment_user:2}.to_yaml, expires: 2.hour.from_now }

And to read it back just process the cookie value through: YAML.load

But you should remember that an individual cookies size is limited to 4K bytes (and actually even less, as signing the cookie increases the cookies value size), so you can't just put there as much data as you want. Thus, if all you need to store is some numbers you may store them in a more compact format e.g. [1, 2].to_json.

And on the second point: you can't really append anything to the cookie, but you can read whatever is stored in the cookie and merge it with the data you were going to append and then set the cookie again.

You can do something like this:

if cookies[:comment_data]
  existing_data_string = cookies[:comment_data]
  existing_data = YAML.load(existing_data_string)
else
  existing_data = {...}
end
existing_data.update(comment_number: 1234)
cookies.signed[:comment_data] = { value: existing_data.to_yaml, expires: 2.hour.from_now }

Upvotes: 3

Related Questions