【问题标题】:Rails pattern for conditionally displaying fields用于有条件地显示字段的 Rails 模式
【发布时间】:2014-05-12 17:08:27
【问题描述】:

我发现自己一遍又一遍地重复这种类型的代码。

<% if !@model.property.blank? %>
    <label>Property</label>
    <div><%= @model.property %></div>
<% end %>

目标是仅当且仅当值存在时才输出标签和属性值。我发现多次重复此代码会使扫描源代码变得困难。这可以减少并更简洁吗?可以应用什么模式来简化编码?

【问题讨论】:

    标签: ruby-on-rails design-patterns ruby-on-rails-4


    【解决方案1】:

    你可以为你创建一个助手,它会自动处理这些测试:

    # 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 Pattern。这很有趣,但对于您想要实现的目标来说可能太深了:

    【讨论】:

    • 这太棒了。演示者模式看起来很有趣,但我认为你是对的,因为它对我目前的情况有点过分。
    【解决方案2】:

    您可能希望将其提取到帮助方法中,您可以在其中放置现有逻辑并调用该帮助方法。

    def print_property_if_present(model)
      "<label>Property</label><div>#{model.property}</div>" if model.property.present?
    end
    

    不要忘记调用 html_safe 以 HTML 可打印格式呈现输出。 希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2012-02-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 2010-09-13
      • 2011-01-23
      相关资源
      最近更新 更多