Hello,
Im in the process of working my way through the 2.ed of the agile book.
As many of you already know, the book goes through the regular
development cycle of the Depot application. I have hit a wall
when they started talking about the sessions and the exact mechanics of
how an item is added to the session.
The code looks like this:
depot/app/controllers/store_controller:
def add_to_cart
@cart = find_cart
product = Product.find(params[:id])
@cart.add_product(product)
end
private
def find_cart
session[:cart] ||= Cart.new
end
end
depot/app/models/cart.rb
class Cart
attr_reader :items
def initialize
@items = []
end
def add_product(product)
@items << product
end
end
depot/app/views/store/add_to_cart.rhtml
Your Pragmatic Cart
-
<% for item in @cart.items %>
- <%= h(item.title) %> <% end %>
So, this is what I understand what is happening:
When the “add to cart” button is clicked, the add_to_cart method is run
and a hash is either retrieved or created (not sure exactly how this
work). Does Cart.new mean that it goes into the model Cart and creates
a new item? Does this also mean that the initialize method inside the
Cart model is run?
Also, the line product = Product.find(params[:id]) How come they arn’t
using an @ sign infront of the product?
What are the mechanics of the line @cart.add_product(product)?
The line @cart.items, is the items referring to the line attr_reader
:items?
When is the initialize method in the model used?
Any help on this topic would be greatly appreciated! Thanks in advance!