Reputation: 9722
I have a layout with two <ul>'s that are floated and I wanted to have a some-what even number of items in each ul.
So, I wanted to break up my collection in half, and have one half in the first, and one in the other...
Originally I started thinking, ok I could have my view do:
<ul>
@collection[0..(@collection.to_f / 2).ceil].each do
<li> ... </li>
end
</ul>
<ul>
@collection[(@collection.to_f / 2).ceil..-1].each do
<li> ... </li>
end
</ul>
but that's pretty unattractive.. So then I started thinking about writing a helper to do that, but then I ended up just making scopes in my model:
scope :first_half, {:limit => (count.to_f / 2).ceil}
scope :last_half, {:offset => (count.to_f / 2).ceil}
<ul>
Collection.first_half.each do
<li> ... </li>
end
</ul>
<ul>
Collection.last_half..each do
<li> ... </li>
end
</ul>
but I felt like maybe that's not ideal since the view is the only thing referencing those scopes?
Upvotes: 1
Views: 75
Reputation: 4115
I did this exact same thing about a month ago. I wrote an amazing extention to Enumerable
to be able to split the collection into groups of N, and then realized ActiveSupport already provided exactly that (almost).
Take a look at in_groups(number, fill_with = nil)
it will split an array into number groups, perfect for the view :)
Upvotes: 4
Reputation: 6165
I agree that you should be defining a view helper rather than a scope for your model. You could make the syntax nicer if you define view helpers rather than writing it inline.
# collection_helper.rb
def first_half(collection)
collection[0..(collection.to_f / 2).ceil]
end
# index.html.erb
<ul>
first_half(@collection).each do
<li> ... </li>
end
</ul>
Upvotes: 1
Reputation: 7127
Better to do something like:
Collection.each_slice(Collection.length / 2) { |half|
<ul>
half.each do
<li> ... </li>
end
</ul>
}
Granted, if you have an odd number of entries in your collection, you will end up with 3 lists.
Upvotes: 1