Random images helper for Rails

Here is how to make random images generation for your website.

First you must put your images in a folder /public/images/random_images or what ever.

Second you put images there and mark the filenames with a prefix, which image to which section will be visible on.

index_bottom_1.jpg -> for the index page on the bottom :)

index_bottom_2.jpg -> for the index page on the bottom

featured_art_1.jpg -> some panel.

featured_art_2.jpg -> some panel.

and so on…

Paste this method in your base controller. This method will be called to make list for a specific image folder and “filter” the images that are supposed to be showed in the different regions in @variables.

  before_filter :init_random_images
  protected # :) be carefull for this if you copy paste
  def init_random_images
    # collect some static images
    web_root = "images/imagestorage/random_images"

    all_images = Dir["#{RAILS_ROOT}/public/#{web_root}/*.jpg"]

    @random_head_images = []
    @random_indexbtm = []
    @random_featured = []
    @random_sales = []
    @random_services = []
    @random_framing = []
    @random_artistcollection = []
    all_images.each do |f|
      if File.stat(f).file?
        @random_head_images << ("/#{web_root}/" + File.basename(f)) if f =~ /head_images_/
        @random_indexbtm << ("/#{web_root}/" + File.basename(f)) if f =~ /indexbtm_/
        @random_featured << ("/#{web_root}/" + File.basename(f)) if f =~ /featured_/
        @random_sales << ("/#{web_root}/" + File.basename(f)) if f =~ /sales_/
        @random_services << ("/#{web_root}/" + File.basename(f)) if f =~ /services_/
        @random_framing << ("/#{web_root}/" + File.basename(f)) if f =~ /framing_/
        @random_artistcollection << ("/#{web_root}/" + File.basename(f)) if f =~ /artistcollection_/

Then paste this as a helper or in the base controller, to use it in your views. The method will give you from the images array, count number of images.

  helper_method :get_random_image
  def get_random_image(images, count)
    requested_images = []
    images_copy = images.clone
    [images_copy.size, count].min.times do
      index = rand(images_copy.size)
      requested_images << images_copy[index]

here is an example how to use it.

<div id="static_logo" style="background:url(<%= get_random_image(@random_sales, 1) %>) no-repeat scroll left top;">

Future optimization

Put some caching, not to make


on every request.

10x Bl8cki to the nice code optimizations :)

1 Comment

  1. images.sort_by { rand } [0..count]

Comments are closed.

© 2024 Gudasoft

Theme by Anders NorénUp ↑