I am reading Agile Web Development with Rails (4th ed.) and I have found the following code
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_cart
Ca开发者_如何学运维rt.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
end
Since I am a Java developer, my understanding of that part of code is more or less the following:
private Cart currentCard(){
try{
return CartManager.get_cart_from_session(cartId)
}catch(RecordNotFoundEx e){
Cart c = CartManager.create_cart_and_add_to_session(new Cart())
return c;
}
}
That what strikes me is that the exception handling is used to control normal application flow (lack of Cart is perfectly normal behaviour when user visits Depot application for the first time).
If one takes any Java book, they say that this is a very bad thing to do - and for a good reason: error handling shouldn't be used as a replacement for control statements, it's kind of misleading for those who read code.
Is there any good reason why such a practice is justified in Ruby (Rails)? Is this a common practice in Ruby?
Rails is in no way consistent in its use of exceptions. find
will raise an exception if no object is found, but for saving you can choose what behaviour you want. The most common form is this:
if something.save
# formulate a reply
else
# formulate an error reply, or redirect back to a form, or whatever
end
i.e. save
returns true or false. But there is also save!
which raises an exception (adding an exclamation mark to the end of a method name is a Rubyism for showing that a method is "dangerous", or destructive, or simply that it has side-effects, the exact meaning depends on the context).
There is a valid reason for why find
raises an exception, though: if a RecordNotFound
exception bubbles up to the top level it will trigger the rendering of a 404 page. Since you usually don't catch these exceptions manually (it's rare that you see a rescue ActiveRecord::RecordNotFound
in a Rails app), you get this feature for free. In some cases though, you want to do something when an object does not exist, and in those cases you have to catch the exception.
I don't think that the term "best practice" actually means anything, but it is my experience that exceptions aren't used for control of flow in Ruby anymore than in Java or any other language I have used. Given that Ruby doesn't have checked exceptions, you deal with exceptions much less in general.
In the end it's down to interpretation. Since the most common use case for find
is retrieving an object to display it, and that the URL for that object will have been generated by the application, it may very well be an exceptional circumstance that the object cannot be found. It means that either the application is generating links to objects that don't exist, or that the user has manually edited the URL. It can also be the case that the object has been removed, but a link to it still exist in a cache, or via a search engine, I would say that that too is an exceptional circumstance.
That argument applies to find
when used as in your example, i.e. with an ID. There are other forms of find
(including the many find_by_*
variants) that actually search, and those don't raise exceptions (and then there is where
in Rails 3, which replaces many of the uses of find
in Rails 2).
I don't mean to say that using exceptions as control of flow is a good thing to do, just that it's not necessarily wrong that find
raises exceptions, and that your particular use case is not the common case.
For the specific use case, you can simply do
def current_cart
cart = Cart.find_or_create_by_id(session[:cart_id])
session[:cart_id] = cart.id
cart
end
This may seem like it will set a specific id
for a new record it creates, but since id
is always a protected attribute, it will not be set for a new record. You will either get the record with the specified id
, or if that doesn't exist, a new record with a new id
.
I think I'd do something like the following (including caching the current cart so it isn't loaded from the database each time the method is called):
def current_cart
@current_cart ||= begin
unless cart = Cart.find_by_id(session[:cart_id])
cart = Cart.create
session[:cart_id] = cart.id
end
cart
end
end
精彩评论