Hi all,
the code on page 117 to get the of create a cart object is:
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
Since I’d expect to not find a cart, I think it’s not very exceptional to not find a cart.
Therefore, I would probably tend to not using an exception to control the program flow and use code like this instead:
def set_cart
@cart = Cart.find_by(id: session[:cart_id])
return unless @cart.nil?
@cart = Cart.new
session[:cart_id] = @cart.id
end
Or maybe this:
def set_cart
@cart = Cart.find_by(id: session[:cart_id])
if @cart.nil?
@cart = Cart.new
session[:cart_id] = @cart.id
end
end
I must say that I also do like the
def …
# …
rescue …
# …
end
notation (a lot), provided that the rescued behaviour is in fact exceptional.
Am I wrong? What are other people thinking about this?