Random Image Rotation in ROR

It’s pretty easy to accomplish random image rotation in ROR. 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(
).delete_if { |x| !image_files.index(x[-4,4]) }

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

<img src=”./images/rotate/<%= random_image %>” />

And that’s all there is to it.

Permanent link to this article: https://blog.openshell.in/2011/01/random-image-rotation-in-ror/

Leave a Reply

Your email address will not be published.