views:

26

answers:

1

I would like to do something like using instance variables

def index
 @balance=1000
enb

def increment
 @balance+=1
end 

what kind of variable should i use?

+1  A: 

There are different ways to interpret your question, not sure which you meant:

All actions (in the same or different controllers) can use instance variables with the same name. But only 1 action is called per HTML request/response cycle.

If you want an instance variable to be set in one action and have the same value in another action (as part of a different request from the same web browser), use the Session store. Eg

def index
   @balance=1000
   # @balance can be used in views
   session[:balance] = @balance # now stored for the rest of the user's session
end

def increment
   @balance = session[:balance] # initialize
   @balance += 1
   session[:balance] = @balance # update
end 

####################################################

# a DRYer way is to use a filter to set the value
# Added, also we set the value to 0 if nil so it can later be added to.
# Remember that nil + 1 => error. 
before_filter :load_balance
def load_balance
  @balance = session[:balance] || BigDecimal.new('0') # use BigDecimal
                                                      # for money calculations
end

# the filter can be set per controller.
Larry K
whats the point to use instance variables here with session?cant we just use only sessions ?eg (session[:balance]=session[:balance].to_i+!) thank you for your helps!!is there another alternative?
fenec
Yes, you can do that. But 1) usually the idea is to separate out the use of the values (instance values) from the storage of the values (the session object). Also, 2) it is not appropriate to access the session from the view. -- You can do it, but it breaks MVC. And 3) You may want to later store the @balance elsewhere. So you should isolate the storage/retrieval to specific methods. Re alternative: yes, you could store the balance in an account or user object, as appropriate. That way it will be associated/stored over the long-term, not just for the current browser session
Larry K