Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 用于有条件显示字段的Rails模式_Ruby On Rails_Design Patterns_Ruby On Rails 4 - Fatal编程技术网

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


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

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可打印格式呈现输出。
希望这有帮助

这太棒了。演讲者模式看起来很有趣,但我认为你是对的,这与我目前的情况有点不符。