Skip to content

Instantly share code, notes, and snippets.

@jk1dd
Last active April 3, 2017 17:00
Show Gist options
  • Save jk1dd/71cbf9003fbf1b6b323c1ed617959554 to your computer and use it in GitHub Desktop.
Save jk1dd/71cbf9003fbf1b6b323c1ed617959554 to your computer and use it in GitHub Desktop.

Sessions, Cookies, and Flashes

  1. If we didn't have cookies and sessions, what would happen?

Since HTTP is stateless, it would be difficult to give the user feedback on whether they successfully interacted with the database. It would also not be possible to save settings, shopping carts, or other information between requests.

  1. What is a cookie?

A cookie is a key/value pair, acts like a hash but it isn't really. It is stored in the user's browser and sent with each request. It is often used to store things like simple preferences settings, where a user left off on the page, and other non-sensitive information. They have an expiration date, or can be set to be cleared when the browser closes (I think).

  1. What's the difference between a cookie and a session?

A session is secure and serialized. It works similarly to a cookie (as a hash that can be accessed from the controllers or views), and ends when the session ends. I expect this would be used to persist more senistive data, where the identity of the user is important.

  1. What's serialization and how does it come into play with sessions?

Only the app knows the "key" to understand the serialized data in a session, this is stored in secrets.yml file.

  1. Why would we want to store a user id in a session?

User id would be important in a session to verify the request in coming from where we expected?

  1. What is a flash? How long does a flash have before it expires?

Flash is like a session that self-destructs after it is displayed. It is available to the next view, but then gets discarded. It is useful for things like feedback on the success/failure of creating a record through a form. Also behaves like a hash.

  1. What syntax would I use to add a user_id key and value to the session?

session[:user_id] = 1 <- but I am not sure where this would go, maybe in the controller?

  1. What does "HTTP is stateless" mean?

The server knows nothing about the request that came in before or what will come next - if you want to hold over information for any length of time, you have to build it into your program. Cookies, sessions, and flashes provide a way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment