Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Dir.glob to list assets in Rails 3.1?

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!

like image 687
thoughtpunch Avatar asked Nov 04 '11 13:11

thoughtpunch


People also ask

What is the use of Glob file in Ruby?

"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.

What is the difference between OS listdir and OS Glob?

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.

How do I match all files in a directory using Glob?

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.

How to get the path relative to the directory specified in rails?

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.


1 Answers

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
like image 187
Dylan Markow Avatar answered Oct 17 '22 08:10

Dylan Markow