Array#in_groups_of in Rails
Posted on
03 Jun 12:45
Array#in_groups_of, where have you been all of my life?
Today we were presented with the following problem in HAML:
We wanted several list items to be outputted in lists of 3.
Fairly simple in ERB, it would be something like this:
<% @activities.each do |a| %>
<% if @i%3 == 0 >
<ul>
< end >
<li><%= link_to a.name, a %>
<% if @i%3 == 0 >
</ul>
< end >
<% @i += 1 >
However, HAML would prove to be a problem due to indentations.
Consider the following code:
-@activities.each do |a|
-if @i%3 == 0
%ul
%li=link_to a.name, a
-@i += 1
This won't work, since our %li would be outside of our %ul. We can't put it inside without having either incorrect nesting or HAML indentation errors.
We asked help from stackoverflow (gotta love this site) and someone proposed using Array#in_groups_of:
-@activities.in_groups_of(3, false) do |activity_group|
%ul
-activity_group.each do |activity|
%li=link_to activity.name, activity
Worked like magic. in_groups_of saved the day.
More information can be found on Railscast.
