Rails view template for a gallery

I am totally new to rails, so sorry for the trivial question!

I have an object, gallery, that contains a list of images. I want to
display these images in a table with 4 columns and as many rows as it
takes, closing the final table row at the end.

What is the best way todo this?

I can do it (mostly, the final table row is still left open) using the
following template, but it seems a bit hackish in places:

<%= @gallery.name -%>

<% i = 1 for img in @gallery.images -%> <%= if i == 1 || (i-1)%4 == 0 "" else "" end -%> <%= "" if i%4 == 0 -%> <%= i += 1 "" -%> <% end -%>

Is there a better way?

stephen O’D wrote:


Is there a better way?

Generally, you’ll want to ask Rails-specific questions on the Rails
mailing list, as this is the Ruby mailing list.



How about using Enumerator#each_slice (or Rails’ #in_groups_of):

<%= @gallery.name -%>

<% @gallery.each_slice(4) do |slice| %> <% slice.each do |image| %> <% end %> <% end %>
<%= image_tag(image) %>

– Brian

I was writing to my local Ruby user group mailing list about it and it
dawned on me: I should just partition it! Brian beat me too it, though
(good thinking). I didn’t find documentation on Enumerable#each_slice,
but I did find Array#slice which should do the same thing (though, I
just noticed the documentation was for 1.6, so that’s probably my

But, in retrospect, I’d do what Brian did: it’s short, readable, and
maybe faster? (I’d have to benchmark it.)


I’ll be honest, I think this is Ruby-centric enough because it really
comes down to basic looping and Erb, so I’ll take a stab at it!

<%= @gallery.name -%>

<% ((@gallery.length / 4) + (((@gallery.length % 4) > 0) ? 1 : 0)).downto(1) do %> <% 4.downto(1) do %> <% end %> <% end %>

That basically figures out how many rows (based on the length divided
by 4, plus 1 if there were any leftovers) and then loops through them.
Then, for each row, we loop four times and for each iteration, we
shift off the front element to go from beginning to end (instead of
pop, which will pull if off the end).

I like this solution a bit better because it uses a very heirarchical
structure much like the way the data will be. Plus, I don’t have to
embed any HTML into Erb!

Hope this helps,


Matt T. wrote:

Guys thats great - I new there had to be a tidier way!

Can I also say thats about the most helpful response I have ever had on
usenet after posting in the wrong group!

From now on I put rails questions in the rails group.



This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs