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?

P.S. Order of actions matters.

Answers


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

Need Your Help

Deploying war file in STS using gradle

java deployment war gradle sts-springsourcetoolsuite

I have a web project in STS, that iam looking to deploy in Tomcat. The build file for the project is written in GRADLE. Using GRADLE'S build script, a war file is generated in build/libs.

How to set Custom keyboard specific to only a UItextfield

iphone keyboard uikeyboard

How to set Custom keyboard specific to only a UITextField? When I am changing using this method, all the keyboards in my application are changed to this new custom keyboard. I added: