My question is based on the following code from the agile book:
File: depot_f/app/controllers/store_controller.rb
private def find_cart session[:cart] ||= Cart.new
File: depot_f/app/models/cart.rb
class Cart
֒attr_reader :items def initialize @items = end
def add_product(product) @items << product end
File: depot_f/app/controllers/store_controller.rb
def add_to_cart @cart = find_cart product = Product.find(params[:id]) @cart.add_product(product) end
Ok, so correct me if Im wrong, but dont instance variables only last till the end of the method?
So how is it possible to keep appending items to the instance array named @items?
Sorry for the newbie question, but I need to get this cleared up so I can move on.
You're right about instance variables.. but way up at the top is the line:
session[:cart] ||= Cart.new
This line checks to see if sesion[:cart] exists and if it doesn't, it sets it to a new Cart. Then it returns that cart object (either a new one or from the session). This happens a bit farthe down in the line:
@cart = find_cart
At which point you have a valid @cart which has as instance variables @items as they were saved in the session from the last request.
-philip