Reputation: 5528
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.
Upvotes: 0
Views: 1684
Reputation: 3965
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
Upvotes: 0
Reputation: 4801
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 %>
Upvotes: 1