Ruby (on Rails) nested if statements with or condition

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

<% if A || B %>
  <% if A %>
    <li>Action A</li>
  <% end %>
    <li>Action C</li>
  <% if B %>
    <li>Action B</li>
  <% end %>
<% 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.


In your controller:

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

In your view:

<% if @action_list.count > 0 %>
    <% @action_list.each do |action| %>
      <li><%= action %></li>
    <% end %>
<% 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

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

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

action_list_items = "a", "b"

puts action_list_items.render?
#=> true

action_list_items.each do |item|
  puts item
#=> 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: