Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing state across requests from the same user

I understand that state can be stored across cookies and the session[] hash.

Which of the following can be used to store state ACROSS requests from the same user? Select all that apply.

  1. Cookies
  2. The session[] hash
  3. Instance variables set by a controller method
  4. Class variables set by a controller method

The answer to this quiz question was (1) and (2). My question is: Why can't (3) and/or (4) store state across requests from the same user?

like image 984
user86408 Avatar asked Aug 01 '13 23:08

user86408


1 Answers

(3) cannot store state across requests. Every time a request comes into your Rails app, an instance of your controller is created and the appropriate action method is called on it. Once the request has been handled, the controller instance is thrown away and a fresh one is created for the next request.

(4) can technically store state across requests, but the data will be shared across all instances of your controller regardless of which user is making the request. It also cannot be accessed from other controllers, is lost if the server is restarted, and if multiple instances of your Rails app are running at once (quite common in production scenarios), the contents of the class variable will not be shared between them.

Elaboration on why this sort of thing is a bad idea: https://stackoverflow.com/a/1029798/742690

like image 97
DigitalCora Avatar answered Sep 22 '22 12:09

DigitalCora