Cookies

Aldo Portillo - Jul 28 '23 - - Dev Community

Introduction

I was creating an AI chatbot running on GPT using Ruby. I wanted to user to be able to keep a history of their chat without losing the previous answer due to a rerender. This problem helped me understand cookies.

Cookies are a type of web storage that store strings with a key.

require "sinatra/cookies"

cookies.store("key","value") 
Enter fullscreen mode Exit fullscreen mode

When cookies are stored they are stored in the cookie hash. Every property in the hash has a key and a value. The value can only be a string.

What if we want to store a hash or an array?

require "json"
require "sinatra/cookies"

employees = [{"first_name" => "Aldo", "last_name" => "Portillo", "occupation" => "Bartender"}]

cookies["employees"] = JSON.generate(employees)
Enter fullscreen mode Exit fullscreen mode

We need to convert the hash/array to a string. Luckily the JSON Gem has a method for that.

We now have a cookie with key employees and a string value that used to be an array. What if we want to add another hash to the array?

require "json"
require "sinatra/cookies"

#Get string from cookies and convert it to an array
employees = JSON.parse(cookies["employees"])

#Add a new employee
employees.push({"first_name" => "John", "last_name" => "Burn", "occupation" => "Server"})

#Modify cookie 
cookies["employees"] = JSON.generate(employees)
Enter fullscreen mode Exit fullscreen mode

We extract the cookie from local storage, Parse the string to convert it to an array again, push the hash into the array and store the mutated array back in as a cookie by converting it to a string.

Quick note

I am declaring the hashes using rocket notation so the keys are strings; as opposed to, symbols. For some reason I don't understand, when the new hash was pushed the keys were symbols and after the next was pushed the previous hash's keys converted to strings. This caused an issue when trying to iterate over the array of hashes since the first n number of hashes' keys were strings and the last hashes' keys were always symbols.

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player