views:

35

answers:

2

Assume that I have a global variable user in application....like this:

  # GET /users.xml
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end    

Is that mean every request, a new @user is created? If every request , an object is created, when will it destroyed? Also, if vistorA go to the web site, a @userA is created, and vistorB go to the web site @userB is created. Will the vistorA have a chance to get the vistorB 's object (@userB)? Also, when will the object release? Thank you.

**Update: the @users is not the global variable, it is a instance variable. So, a question to follow up. How does the server know which @user is belong to which request? Thank you.

+4  A: 

@users is not a global variable it is an instance variable. A new instance of your controller is created to handle each request so the @users for visitor A and visitor B are independent.

mikej
thank, very simple question, updated with a following question. How does the server know which @user is belong to which request? Thank you.
Tattat
As an example, if your `index` action is inside a `UserController` then each request has its own instance of `UserController`. That same instance is used for the duration of the request so within a given request `@users` will always refer to the same object.
mikej
Also, once a request is completed the instance of the controller (and hence its instance variables) are no longer reachable. You need to read up on garbage collection in Ruby though to understand when the objects are released/destroyed.
mikej
+1  A: 

1] @users is not a Global Variable it is a instance variable.its scopre remain upto that method only.

 def index
    @some_variable= "Hello"
    other_method
    redirect_to :action=>'redirect_method'
  end

  def other_method
    #here you get @some_variable ="Hello" as you called this method in index where variable is initialise
  end

  def redirect_method
   #here you get @some_variable as you not called this method in index but redirected to this method
  end

2] for every user @users will be different as each request handle by server independently

Salil
Presumably in `redirect_method` you mean that you **don't** get `@some_variable`? Also, it is a bit confusing to suggest that the scope of the variable is the method - that makes it sound like a local variable.
mikej
So, when will the object release?
Tattat