4

Question 1:

What is the scope of an instance variables in Rails actions (methods). Does each connection to the server form a new instance of a controller?

For example:

  • User_A loads a 'setter' page, causing a random instance variable called @randInt to be generated.
  • User_B (from another PC elsewhere) loads a 'getter' page, requesting @randInt.

Will User_B retrieve the @randInt set by User_A? Or is that instance variable unique to User_A's connection?

Question 2:

Question 2 is the same as question 1, but using @@randInt instead. If the answer to Question 2 is, "yes, both users can see this value," is it an acceptable practice to use global variables in Rails to store temporary data that you want to share among multiple users?

1 Answer 1

2

Question 1: No, instance variables are shared only in the instance, where 'instance' refers to the instance of the controller, and so these variables only last one request (so User_B will receive a different @randInt).

Question 2:: @@ variables are not global variables, $ variables are. @@ are class variables. As the link explains, different machine instances (such as if you're using FCGI) will not share global ($) variables, so don't use them.

If you require global constants, set them in the config. Global variables are probably better left in the database (I can see a use for them, such as site settings, but the uses seem best suited to use with a database).

You could use class variables as persistant instance variables, but again you might be better of using a database to store such values as you're not guaranteed against your classes being reloaded (therefore resetting any class variables).

Sign up to request clarification or add additional context in comments.

2 Comments

I probably wouldn't use the term session as it provokes a confusion with the actual rails sessions. Actually, each request creates an new controller instance where the instance variables are valid for the duration of the request.
I considered it, but should of thought harder. You're absolutely right, updated the answer to clear up any confusion (hopefully).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.