I am trying to choose an image randomly from a sub directory inside my /app/assets/images
directory using the Dir.glob()
command, and then display it with an image_tag
. Somehow I can't get it to work.
Here's my code:
- @badges = Dir.glob("app/assets/images/badges/*")
= image_tag @badges.sample
Which produces the following error:
ActionController::RoutingError (No route matches [GET] "/assets/app/assets/images/badges/produce.png"):
As you can see the asset pipeline is inserting an "/assets" in front of the directory. Alright Rails, I'll meet you halfway here. So next I try removing /app/assets
from the query 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!
"Globbing" files (with Dir.glob) in Ruby allows you to select just the files you want, such as all the XML files, in a given directory. Even though Dir.blog is like regular expressions, it is not. It's very limited compared to Ruby's regular expressions and is more closely related to shell expansion wildcards.
Glob functions similarly to the os listdir function, but you can search for all files or those matching particular conditions. A major benefit of the glob library is that it automatically includes the path to the file in each item.
A glob consisting of only the asterisk and no other characters or wildcards will match all files in the current directory. The asterisk is usually combined with a file extension if not more characters to narrow down the search. ** – Match all directories recursively.
If you execute glob within a block passed to Dir.chdir, you get the paths relative to the directory specified by Dir.chdir… like this… Gems are libraries in Rails that generally enable you to write the application code faster and thereby making a great product in far lesser time.
Dir.glob
is going to return images with a relative path, so your produce.png
file will be returned as:
`app/assets/images/badges/produce.png`
However, you need to pass only the badges/produce.png
part to image_tag
. You need to remove the stuff before this:
= image_tag @badges.sample.gsub("app/assets/images/", "")
You may want to stick this in a helper instead:
def random_badge
badges = Dir.glob("app/assets/images/badges/*")
image_tag badges.sample.gsub("app/assets/images/", "")
end
and then in your view:
= random_badge
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With