简体   繁体   中英

Ruby (on Rails) nested if statements with or condition

I was looking for a way to improve this piece of code:

<% if A || B %>
  <a></a>
  <ul>
  <% if A %>
    <li>Action A</li>
  <% end %>
    <li>Action C</li>
  <% if B %>
    <li>Action B</li>
  <% end %>
 </ul>
<% end %>

this involves to evaluate A, eventually B and then A again and B again. Any idea on how to improve that code?

PS Order of actions matters.

In your controller:

@action_list = []
if A || B
  @action_list << "Action A" if A
  @action_list << "Action C"
  @action_list << "Action B" if B
end

In your view:

<% if @action_list.count > 0 %>
  <a></a>
  <ul>
    <% @action_list.each do |action| %>
      <li><%= action %></li>
    <% end %>
  </ul>
<% end %>

I'd go with the same approach as msergeant, but stick it in a class like so:

class ActionListItems

  def initialize(a = nil, b = nil)
    @a = a
    @b = b
  end

  def render?
    !!(@a || @b)
  end

  def each
    yield "Action A" if @a
    yield "Action C"
    yield "Action B" if @b
  end
end

action_list_items = ActionListItems.new "a", "b"

puts action_list_items.render?
#=> true

action_list_items.each do |item|
  puts item
end
#=> Action A
#=> Action C
#=> Action B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM