Random Image Rotation in Rails

It’s pretty easy to accomplish random image rotation in Rails. This is a simple example of how it can be done, and of course there are ways to make it better (for example, this snippet will only rotate and display .jpg, .gif, and .png files).

First, create a folder – let’s name it “rotate” – inside of the /public/images/ folder in the rails project directory.

Next, drop a few images in the folder (ideally all of the same dimensions).

Then, add this method to your application_helper.rb file in the /app/helpers folder:

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

Finally, include the following line in any .rhtml file to display a random image:

<img src="/images/rotate/<%= random_image %>" />

And that’s all there is to it.

More articles in the Archive →