I'm a total beginner at Ruby. I've more experience with PHP. I'm trying
to figure out how to read this method:
def empty_cart
@cart = find_cart
@cart.empty!
@items = @cart.items
redirect_to(:action => 'index')
end
What does
@cart.empty!
mean?
And does this:
redirect_to(:action => 'index')
mean simply that the action index should be called?
What does
@cart.empty!
mean?
Simple. It calls the method called 'empty!' on the @cart object.
It's a convention in ruby that methods that modify an object in place end in '!' and methods that return a boolean end in '?'.
And does this:
redirect_to(:action => 'index')
No. This sends a 302 redirect to the browser so that it then requests the index action.
Cheers,
Pete Yandell
Hi --
What does
@cart.empty!
mean?
Simple. It calls the method called 'empty!' on the @cart object.
It's a convention in ruby that methods that modify an object in place
end in '!' and methods that return a boolean end in '?'.
That's sort of a convention-within-a-convention. The basic convention
is that !-methods are "dangerous", compared to their non-dangerous
counterparts. The "danger" can, but doesn't have to, take the form of
modifying the receiver.
There are also lots of methods that change their receivers but don't
end in !, such as Array#pop, Hash#delete, etc.
David
What does
@cart.empty!
mean?
Basically, it calls the empty! method on @cart object. Without knowing what class @cart is, it's impossible to say anything about what it actually does. However, judging by the name, I would guess it empties the cart. The exclamation mark is a naming convention that indicates that the object itself is being modified (as opposed to returning a modified copy of the object).
And does this:
redirect_to(:action => 'index')
mean simply that the action index should be called?
Pretty much, but not exactly. It adds a redirect header to the response, indicating that the connected client should initiate a new request, this time for the url identified by :action => 'index'.