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 val开发者_如何学Pythonue," is it an acceptable practice to use global variables in Rails to store temporary data that you want to share among multiple users?
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).
精彩评论