The Depot "Add to Cart" sessions question (2.ed agile book)

Hi Kristen, please see my answers to your questions below. Also, I
would recommend the you read:

Programming Ruby Chapters 1 - 7


Ruby For Rails

Good luck,



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 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?

Actually, creates an instance of the Cart class. For example,

@cart =

Now, when 'new' is called on the Cart class, the Cart's initialize
method is called. This intern initializes the items array to be empty
(i.e. []). Then the new instance is returned and assigned to @cart in
the example above.

Also, the line product = Product.find(params[:id]) How come they arn't
using an @ sign infront of the product?

The reason for this is that find is a class method. Thus, we invoke
class methods
using the following syntax:


e.g. Product.find

If it were an instance method, then we would have something similar to
the following: # where name is an attribute accessor defined on the class Product

What are the mechanics of the line @cart.add_product(product)?

@cart is an instance of the Cart class and we're passing a message to
this instance called add_product which takes product instance as a
parameter. In short, we're adding a product to the @cart instance.

The line @cart.items, is the items referring to the line attr_reader

Yes, this is correct.

When is the initialize method in the model used?

It is invoked anytime that you call new on a class. For example,

@cart =