What would you recommend as the best way to refactor these two bits of view code?
<%if Supplydetail.find_all_by_isbn_id(@isbn).first.nil? %>
<%else%>
<%if Productavailability.find_by_code(Supplydetail.find_all_by_isbn_id(@isbn).first.productsupply_supplydetail_productavailability).nil? %>
<%else%>
<li><%= Productavailability.find_by_code(Supplydetail.find_all_by_isbn_id(@isbn).first.productsupply_supplydetail_productavailability).value %></li>
<%end%>
<%end%>
and (using formtastic)
%li.tip
= tooltip(:test, :hover)
= f.input :relatedmaterial_relatedproduct_idvalue, :label => "Related ISBN", :as => :select, :collection => Isbn.all, :label_method => :descriptivedetail_titledetail_titleelement_titlewithoutprefix, :value_method => :productidentifier_idvalue
%li.list
= link_to "Edit list", isbns_path
I have examples of each of these about a bazillion times in my app, and would like to know I’m refactoring in the best way before I dive in to this rather huge job.
First of all, an empty
ifbranch in an if/else usually (but not always!) smells bad so don’t do that, it just makes your code harder to read and understand.Also, you’re computing
Supplydetail.find_all_by_isbn_id(@isbn)andProductavailability.find_by_code(...)twice just to get your<li>output. Don’t do that either.And you might want to push most of that logic into your controller (or maybe a helper depending on where and how often it is used) to cut down on the ERB-noise.
Maybe something like this would serve you (and whoever gets to maintain your code) better; a bit of controller stuff first:
And then in your ERB:
If you’re doing a lot of this sort of thing then you could add a
Productavailability.for_isbnconvenience class method in your model. Then your controller would just need:But I wouldn’t worry about it until you start repeating yourself.
I’m not familiar with formtastic so I can’t help you with that.