Ruby on rails 用于有条件显示字段的Rails模式
我发现自己一遍又一遍地重复这种代码Ruby on rails 用于有条件显示字段的Rails模式,ruby-on-rails,design-patterns,ruby-on-rails-4,Ruby On Rails,Design Patterns,Ruby On Rails 4,我发现自己一遍又一遍地重复这种代码 <% if !@model.property.blank? %> <label>Property</label> <div><%= @model.property %></div> <% end %> 财产 目标是仅当且仅当值存在时才输出标签和特性值。我发现多次重复这段代码会使扫描源代码变得困难。这一点可以简化并变得更简洁吗?什么样的模式可以应用于此以使编
<% if !@model.property.blank? %>
<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 Presenter模式。这很有趣,但对于您想要实现的目标来说可能太深了:
def print_property_if_present(model)
"<label>Property</label><div>#{model.property}</div>" if model.property.present?
end
def打印属性(如果存在)(型号)
如果model.Property.present存在“Property#{model.Property}”?
结束
不要忘记调用html_safe以html可打印格式呈现输出。
希望这有帮助 这太棒了。演讲者模式看起来很有趣,但我认为你是对的,这与我目前的情况有点不符。