10th Dec 2008
Reading directories and outputting results with Ruby on Rails
After searching Google for an hour, and not finding a good example of this, I finally figured it out and decided to write my own. Hope you find this example useful.
I am assuming, if you are reading this, that you need to read a directory in your controller and output the results of the read in the view. You should first know, that the method I am using uses the “public” folder as the root directory for your reading. All the files and directories you are trying to read, must be located within the “public” folder. For the sake of this example, lets assume you are trying to read the contents of the “public/images/” directory, and out put the file paths in your view.
First we start with the code for the controller, my example adds a parameter from the URL to specify which folder within the image folder you wish to read.
Controller Code:
def readImage
@files = Array.new
Dir["images/" + params[:id] + “/*”].each do |x|
@files << x
end
end
In our method, we first create a new Array object for the filenames contained in the diretory.
@files = Array.new
Next, we want to pull the files from the “images/” + params[:id] folder. We use the awesome object oriented nature of Ruby and call the each method on the Dir[] call. In line 2 we push “<<” the value contained in x into the @files array.
Dir["images/" + params[:id] + “/*”].each do |x|
@files << x
end
That is ALL THE CODE YOU NEED for the controller, now its on to the view.
In the view I am just going to show you how to output the data from the @files array. You can decide how you want to use it. You could put this in an img tag, or build out some <a> links to create downloadable files. Basically the following lines are needed.
View Code:
<% @files.each do |p| %>
<%= p %>
<% end %>
In the first line, we again use the object oriented nature of ruby to access the each method in the @files object that we created in our controller.
<% @files.each do |p| %>
From there we output the value for each file path and end our each loop.
<%= p %>
<% end %>
Pretty straight forward huh? If anyone has any questions or comments please let me know.
We love the Ruby on Rails framework here at MasteredMinds and use it to create high quality, low cost websites and web based applications. If you have any questions about our tactics or services, or would like to see some our of work, you can visit our website, www.masteredminds.com.

Man, awesome! This saved me so much time, and I couldnt freakin find anything on google that worked. This worked like a charm! Thanks.
I bookmarked this
Thanks everyone for the great insight and post here.Its great when everyone can share ideas and expirence with others and when it makes a differnce as well.i will be making a contribution here as well.thanks