link_to中的Ruby三元组

时间:2016-10-18 17:42:51

标签: ruby-on-rails ruby refactoring erb

我的基本问题是如何使用三元组将其转换为一行代码?

 <% if tip_off %>
  <%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand-tip-off", rel: "home" %>
<% else %>
  <%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand", rel: "home" %>
<% end %>

我所做的就是在特定条件下更改班级名称。

4 个答案:

答案 0 :(得分:5)

我认为它在两行中更具可读性

<% link_class = tip_off ? "topbar-brand-tip-off" : "topbar-brand" %>
<%= link_to "Dead Man's Snitch", [:homepage], class: link_class, rel: "home" %>

答案 1 :(得分:1)

通过插入类值:

<%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand#{tip_off ? '-tip-off': ''}", rel: "home" %>

答案 2 :(得分:1)

您可以在link_to:

之外进行
<% css_class = tip_off ? "topbar-brand-tip-off" : "topbar-brand" %>
<%= link_to "Dead Man's Snitch", [:homepage], class: css_class, rel: "home" %>

或者你可以用插值

来做
<%= link_to "Dead Man's Snitch", [:homepage], class: "topbar-brand#{'-tip-off' if tip-off}", rel: "home" %>

答案 3 :(得分:0)

您可以使用link_to_if

中内置的导轨
 link_to_if(tip_off, "Dead Man's Snitch", { [ACTION_OPTIONS] }, class: "topbar-brand-tip-off") do
    link_to("Dead Man's Snitch", { [ACTION_OPTIONS] }, class: "topbar-brand") 
 end

docs:http://apidock.com/rails/v4.2.1/ActionView/Helpers/UrlHelper/link_to_if