Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Displaying images at random

I'm trying to display one image based on an if/else statement related to "price". I have 5 folders in my /assets/images directory as follows:

very_bad
bad
ok
good
very_good

Each folder contains multiple images and I would like to grab only one image from the appropriate folder at random, so the user doesn't always have to see the same image.

For example, if the price is less than -2%, I would want to randomly display an image from the "very_bad" folder. If the price is greater than 2%, I would want to randomly display an image from the "very_good" folder.

How would you tackle this issue? Thanks for the help!

like image 286
Kyle Reierson Avatar asked Nov 28 '22 02:11

Kyle Reierson


1 Answers

Once you've determined the folder name (let's use very_good as an example), determine a random number based on the number of images you have. Let's say you have four images in each folder, use rand(4) to get a random number among [0,1,2,3]. Name your images 0.png, 1.png, etc. within each folder. Now you should be able to display one of the images at random, given the folder name, as follows:

<%= image_tag "very_good/#{rand(4)}.png" %>

Since your folder name is probably dynamic, it would look more like this:

<%= image_tag "#{@folder_name}/#{rand(4)}.png" %>
like image 152
hiattp Avatar answered Dec 04 '22 03:12

hiattp