我發現自己一遍又一遍地重複這種類型的代碼。有條件顯示字段的導軌模式
<% if [email protected]? %>
<label>Property</label>
<div><%= @model.property %></div>
<% end %>
目標是隻輸出標籤和屬性值,當且僅當該值存在。我發現多次重複這些代碼使得很難掃描源代碼。這可以減少和更簡潔嗎?什麼樣的模式可以應用於此,以便於編碼?
我發現自己一遍又一遍地重複這種類型的代碼。有條件顯示字段的導軌模式
<% if [email protected]? %>
<label>Property</label>
<div><%= @model.property %></div>
<% end %>
目標是隻輸出標籤和屬性值,當且僅當該值存在。我發現多次重複這些代碼使得很難掃描源代碼。這可以減少和更簡潔嗎?什麼樣的模式可以應用於此,以便於編碼?
你可以爲你創建一個幫手,將處理論文自動測試:
# application helper
def display_if_exists(instance, attribute)
return nil if instance.blank? || attribute.blank?
label_tag = content_tag :label do
instance.class.human_attribute_name attribute.to_sym
end
div_tag = content_tag :div do
instance.try(attribute.to_sym)
end
return (label_tag + div_tag).html_safe
end
而且使用這種方式:
# view
display_if_exists(@user, :username)
一點點改善,選項:
def display_if_exists(instance, attribute, options = {})
return nil if instance.blank? || attribute.blank?
label_options = options.delete(:label)
div_options = options.delete(:div)
label_tag = content_tag :label, label_options do
instance.class.human_attribute_name attribute.to_sym
end
div_tag = content_tag :div, div_options do
instance.try(attribute.to_sym)
end
return (label_tag + div_tag).html_safe
end
並使用選項是這樣的:
display_if_exists(@user, :username, { label: { class: 'html-class' }, div: { style: 'margin-top: 2px;' } })
的另一種選擇是Rails的演示模式。這是非常有趣的,但你要實現的目標可能是太深了:
可能是你想提取這變成一個輔助方法,你可以把現有的邏輯和調用幫助器。
def print_property_if_present(model)
"<label>Property</label><div>#{model.property}</div>" if model.property.present?
end
不要忘記調用html_safe以HTML打印格式呈現輸出。 希望這有助於!
這太棒了。主持人模式看起來很有趣,但我認爲你說得對,因爲我目前的情況有點多。 – Jeff