Using Dir.glob to List Assets in Rails 3.1?

I am trying to select an image randomly from a subdirectory inside my /app/assets/images directory using the Dir.glob() command, and then display it using image_tag . Somehow I can't get it to work.

Here is my code:

 - @badges = Dir.glob("app/assets/images/badges/*") = image_tag @badges.sample 

Which causes the following error:

 ActionController::RoutingError (No route matches [GET] "/assets/app/assets/images/badges/produce.png"): 

As you can see, the asset pipeline inserts "/ assets" in front of the directory. Okay, Rails, I'll meet you halfway. So, I will try to remove /app/assets from the request path to make it work and get the following result:

 - @badges = Dir.glob("images/badges/*") = image_tag @badges.sample ActionController::RoutingError (No route matches [GET] "/assets"): 

What am I doing wrong here? Thanks in advance for your help!

+6
source share
1 answer

Dir.glob will return images with a relative path, so your produce.png file will be returned as:

 `app/assets/images/badges/produce.png` 

However, you only need to pass the badges/produce.png part to image_tag . You need to remove the material before this:

 = image_tag @badges.sample.gsub("app/assets/images/", "") 

Instead, you can use this in a helper:

 def random_badge badges = Dir.glob("app/assets/images/badges/*") image_tag badges.sample.gsub("app/assets/images/", "") end 

and then, in your opinion:

 = random_badge 
+7
source

Source: https://habr.com/ru/post/900776/


All Articles