【问题标题】:How do I cleanly check if a ruby hash has a value before executing code in ERB?在 ERB 中执行代码之前,如何干净地检查 ruby​​ 哈希是否具有值?
【发布时间】:2019-08-18 13:49:25
【问题描述】:

我有一个加载到 Ruby 哈希中的 XML 对象。目标是在网页中显示来自 Web 服务的一些复杂 XML。

棘手的是,根据从 Web 服务返回的 XML 数据,XML 看起来会有所不同。

我的 ERB 代码看起来像这样......

...
<p>Name:</p><%= @some_hash['root']['data']['name'] %>
<table>
<tr><td><span class="label">Total:</span><%= @some_hash['root']['data']['subdata'] %></td></tr>
<tr><td><span class="label">Rate:</span><%= @some_hash['root']['data']['subdata1'] %></td></tr>
</table>
<table>
    <tr>
      <th>Column A</th>
      <th>Column B</th>
    </tr>

  <% @some_hash['root']['data']['subdata2'].each do |value| %>
    <tr>
      <td><%= @value['A'] %></td>
      <td><%= @value['B']  %></td>
      </tr>
  <% end %>
 </table>
...

我将“@”放在变量前面以检查是否为零。那没有多大作用。我不确定这是否是最好的方法。如何干净地遍历 ERB 并仅在值存在时执行?

【问题讨论】:

  • 可能缺少哪个值以及当前值或缺失值的预期结果是什么?

标签: html ruby erb


【解决方案1】:

Hash#digsafe navigation operator 会这样做:

<% if subdata = @some_hash&.dig('root', 'data', 'subdata') %>
  <tr><td><span class="label">Total:</span><%= subdata %></td></tr>
<% end %>

dig 将尝试提取嵌套值,如果其中任何部分不可用,则返回 nil。如果@some_hash 为nil,则安全导航运算符&amp;. 在调用.dig 时会阻止NoMethodError。

【讨论】:

  • 如果没有 if 这会可靠吗?喜欢 Total:.
【解决方案2】:

使用助手

def data_table(source)
  if subdata = source&.dig('root', 'data', 'subdata')
    h.content_tag :table do
      h.content_tag :tr do
         h.content_tag :td do
           h.content_tag :span, 'Total:'
           subdata
         end
      end
    end
  end
end

erb

<p>Name:</p><%= @some_hash['root']['data']['name'] %>
<%= data_table(@some_hash) %>

【讨论】:

  • 我真的很喜欢这个主意。我不断收到上面的代码“错误数量的参数”。我认为它在 h.content_tag :span?
【解决方案3】:
<% if subdata = (@some_has || {}).dig('root', 'data', 'subdata') %>
  <tr><td><span class="label">Total:</span><%= subdata %></td></tr>
<% end %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多