我发现自己一遍又一遍地重复这种类型的代码。
<% if <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c0d6c4143484940025c5e435c495e5855024e404d4247" rel="noreferrer noopener nofollow">[email protected]</a>? %>
<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 模式。它非常有趣,但对于您想要实现的目标来说可能太深了:
关于ruby-on-rails - 用于有条件显示字段的 Rails 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22794137/