Ruby Instance and Rails Global Variables

Question 1:

What is the scope of instance variables in Rails actions (methods). Each connection to the server forms a new controller instance?

For instance:

  • @randInt loads the 'setter' page, invoking a random instance variable named @randInt .
  • User_B (from another computer in another place) loads the 'getter' page, requesting @randInt .

Will User_B get the @randInt set by User_A? Or is it an instance variable unique to the User_A connection?

Question 2:

Question 2 is the same as question 1, but @@randInt used @@randInt . If the answer to question 2 is “yes, both users can see this value”, is it acceptable to use global variables in Rails to store temporary data that you want to share between multiple users?

Thanks, advanced

Derek

+4
source share
1 answer

Question 1 : No, instance variables are only shared in the instance where the "instance" refers to the controller instance, and therefore these variables save only one request (so that User_B will get another @randInt ).

Question 2:: @@ variables are not global variables, $ variables are . @@ are class variables. As the link explains, different computer instances (for example, if you use FCGI) will not use global ( $ ) variables, so do not use them.

If you need global constants, set them in config. Global variables are probably best left in the database (I can see their use, such as site settings, but their use seems to be best suited for use with the database).

You can use class variables as constant instance variables , but again you might be better off using a database to store values ​​such as you are not guaranteed to reload your classes (so reload any class variables).

+2
source

All Articles