Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby each, different action depending on index, with a pattern?

Tags:

ruby

erb

Ok so my title may be confusing. What I want to do is to loop through a collection of models, and for the first two, render a template, for the next four render a different template and next two render the same template as for the first ones, and so on.

Like this:

  <% ads.each do |ad| %>
    <% # if it's 1-2, 7-8, 13-14 and so on render as big' %>
      <%= render 'front/home/big_ad', ad: ad %>
    <% # if it's 3-6, 9-12, 15-18 and so on render as small' %>
      <%= render 'front/home/small_ad', ad: ad %>
    <% end %>
  <% end %>

What would be the cleanest way to accomplish this?

like image 611
Yeggeps Avatar asked Jun 27 '12 14:06

Yeggeps


1 Answers

If your groups would be even long, then you could use in_groups_of command, and alternate between them, but with these specifications, the easiest way is this:

<% ads.each_with_index do |ad, index| %>
  <% if (index % 6 < 2) %>
    <%= render 'front/home/big_ad', ad: ad %>
  <% else %>
    <%= render 'front/home/small_ad', ad: ad %>
  <% end %>
<% end %>
like image 126
Matzi Avatar answered Oct 13 '22 21:10

Matzi