sowasred2012
sowasred2012

Reputation: 735

Ordering entries from a loop by type

I'm writing this in Rails but I suspect the logic isn't Rails-specific - I have a list of entries that are all one of two types, photo and video.

At the moment I have a loop that is running through the list in reverse date order, outputting a mix of the two types. Below is an example of the loop I have, it's not the actual code but the logic is the same:

post_count = 1
 if post_count < 2
    if post.type == 'photo'
       <div>post.title</div>
       post_count = post_count + 1
    end
 else
    if post.type == 'photo'
       <div>post.title</div>
       post_count = post_count + 1
    elsif post.type == 'video'
       <div>post.embed_code</div>
       post_count = post_count + 1
    end
 end

This is close to what I want because I want the two types to be mixed to a certain degree, but I wanted to know if it was possible to have the loop pull out the first two photo entries and render those first, then output the rest of the list as normal, including any video entries that may have appeared earlier in the list.

That sounds a bit convoluted to me, so here's a diagram, with the desired result on the right:

List

Thanks in advance.

Upvotes: 0

Views: 73

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

Hmm not sure if it is what you are looking for, but take a look:

@posts.select{ |post| post.type == 'photo' }.first(2).each do |photo_post|
  @posts.delete_if{ |post| post == photo_post }

  # display photo_post
  # <div>post.title</div>

@posts.each do |post|
  post.try(:title) || post.try(:embed_code)

This code assume that @posts is a list of Photos/Videos ordered as your wishes (by date in general). It should not support the nil cases.

Upvotes: 1

Related Questions