我有這個討厭的,如果在鐵軌/ else語句查看:重構醜陋的if/else語句在Rails視圖
<% if question.field_type == "text_area" %>
<%= f.text_area :content, :class=>"form-control question-field", :data => {:question => question.id, :filter=> @filter}, :value=> question.answer(@assessment).try(:content) %>
<% elsif question.field_type == "date" %>
<%= f.date_select :content, { :order => [:year, :month, :day], :prompt => { :day => 'day', :month => 'month', :year=> "year" }, :end_year=> Date.today.year, :start_year => Date.today.year - 2 }, {:class => "question-field", :data => {:question => question.id, :filter=> @filter}, :value=> question.answer(@assessment).try(:content)} %>
<% elsif question.field_type == "text_field" %>
<%= f.text_field :content, :class=>"form-control question-field", :value=> question.answer(@assessment).try(:content), :data => {:question => question.id, :filter=> @filter} %>
<% elsif question.field_type == "dropdown" %>
<%= f.select :content, options_for_select(question.options), { :prompt => "Choose One..." }, :class=>"form-control question-field", :value=> question.answer(@assessment).try(:content), :data => {:question => question.id, :filter=> @filter} %>
<% elsif question.field_type == "number" %>
<%= f.select :content, options_for_select(1..10), {:include_blank=> true}, :class=>"form-control question-field", :value=> question.answer(@assessment).try(:content), :data => {:question => question.id, :filter=> @filter} %>
<% elsif question.field_type == "percentage" %>
<h2>100%</h2>
<%= f.range_field :content, :value=> get_percentage(question), :class=> "question-field percentage", :data => {:question => question.id, :filter=> @filter}, :step => 25, :in => 0..100 %>
<% end %>
是否有這個重構,使之更好的好辦法?這段代碼是在每一個領域:
:class=>"form-control question-field", :value=> question.answer(@assessment).try(:content), :data => {:question => question.id, :filter=> @filter}
我是否重構成輔助方法或部分?
爲什麼case語句比if/else更好? –
這不是事實,模板有時是凌亂的。如果我們足夠警惕 - 它們可以乾淨簡單。我會在這裏考慮偏見,因爲這是他們的目的(查看我的答案)。 – meta