Random Images in your Rails App

Ever want to get a random image from a folder in your rails app? Well, here you have it…place this in your application helper:

# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  def random_header_image
    image_files = %w( .jpg .gif .png )
    files = Dir.entries(
          "#{RAILS_ROOT}/public/images/random_image_folder"
      ).delete_if { |x| !image_files.index(x[-4,4]) }
    files[rand(files.length)]
  end  
 
end

Leave a comment