Search code examples
ruby-on-rails-3methodsmodels

How to create an if else statement that cycles through a class in the model


I have a rails app that displays videos. I only want to display videos if they have a thumbnail, so I have this code in model:

  def thumbnail_ready?
    BitsOnTheRun::call('videos/thumbnails/show', video_key: key).thumbnail.status == 'ready' rescue false
  end

and this in my view:

<% if video.thumbnail_ready? %>
...
<% end %>

The problem is, when the thumbnail isn't there, nothing is displayed at all. What I want is for it to check if the thumbnail is available beforefor it gets to the view - somewhere in the model or controller - and only ever pull out thumbail_ready? videos. How can I do this? The current solution doesn't work on arrays.

An alternative would be to keep this solution, but automatically cycle through to the next video with an available thumbnails. I'm also unsure how to do this.

Any advice/help gratefully received - thanks!


Solution

  • Your code sample is a little sparse, but assuming you have a variable @videos containing all your videos, then:

    @videos.select(&:thumbnail_ready?)
    

    will give you an array of those with a thumbnail. You can then iterate over that array to only show thumbnailed videos.

    If I've misunderstood your problem, then let me know and perhaps give a bit more code context.