4

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!

4 Answers 4

10

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" %>
4
  • This is quite good but it does not take into account other file formats, where in some cases quality is lost because of format change.
    – Vantalk
    Commented Oct 13, 2016 at 11:20
  • Recent versions of rails don't require you to specify the extension, so that's an option. But I'd also check out @bevanb's answer below. I'm not sure about the performance consequences of reading from the file system in operations like this but you definitely won't have the extension problem if that's what you mean by format change.
    – hiattp
    Commented Oct 13, 2016 at 23:24
  • This solution requires you to rename the the files, and doesn't consider any image file format other than .png. In the case that image file names (and their generated alt tags) are important, i.e. for SEO or accessibility, this isn't a viable option.
    – Tina
    Commented Aug 18, 2017 at 13:36
  • @Tina yeah per my previous comment, bevanb has a more robust solution below if you don't mind hitting the file system. The naming/formats need to be persisted somewhere so you need to decide if you want to read from the file system, some other persistence layer, or hard code it as I proposed above. It depends on the circumstance.
    – hiattp
    Commented Aug 19, 2017 at 20:08
10

Here's a solution without renaming your images.

Once you know your folder, do this to select a picture within that folder at random:

=image_tag Dir.new(Rails.root.to_s + "/app/assets/images/my-folder").to_a.select{|f|    f.downcase.match(/\.jpg|\.jpeg|\.png/) }.sample
6

You can do this pretty easily using the Dir.glob, and array .sample and .split methods.

Let's say I have all the random images in a folder called ./backgrounds in my Rails image assets folder:

app/assets/images/
└── backgrounds
    ├── beach.jpeg
    ├── bright-flowers-pink-skies.jpeg        
    ├── fall-autumn-red-season.jpg
    └── fjord.jpeg

I can create a helper in ./app/helpers/application_helpers.rb—or wherever you'd like to put the helper—that has the following code:

module ApplicationHelper
  def get_random_image
    image_path_prefix = "app/assets/images/"
    image_files = Dir.glob("#{image_path_prefix}backgrounds/*")
    image_files.sample.split(image_path_prefix)[1]
  end
end

What this does is globs all of the paths inside of ./app/assets/images/backgrounds, returns a random one (using .sample), removes the image path prefix by splitting the string, and returns the end part of it.

Then in your ERB template, you can display the image like so:

<%= image_tag get_random_image %>

This should result in an image tag for a random image being generated. Be careful to pay attention to leading and trailing slashes.

1
  • Thank you for this @Tina, this should be marked as the right answer
    – Slowboy
    Commented Oct 19, 2017 at 12:25
0

Here's a combo of tina and bevan's answers

module ImageHelper
  def random_image(folder)
    image_path_prefix = "app/assets/images/"
    image_files = Dir.new("#{image_path_prefix}#{folder}")
                     .to_a.select { |f| f.downcase.match(/\.jpg|\.jpeg|\.png/) }
    image = image_files.sample
    "#{folder}/#{image}"
  end
end

Use it like this

<%= asset_path(random_image('good/really_good')) %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.