Topic: Removing unwanted and hidden files in a directory list

Does anyone know how to remove unwanted and hidden files in a directory list. I have been unable to find a method. I would actually like to apply the same technique to remove the . and .. that show up when doing a dir.entries() list.

The controller:

def show
    @project = Project.find(params[:id])
   
    @filename_dir = "/uploads/#{@project.cross_streets}"
    @filename_list =  Dir.entries("#{RAILS_ROOT}/public" + @filename_dir)
  end

The view:
<!-- list of files -->
    <ul>
        <% for filename in @filename_list %>
            <li><%= link_to filename, @filename_dir + "/" + filename %></li>
        <% end %>
    </ul>

The output:
    *  .      <-- I'm trying to hide this
    * ..      <!--and this.
    * twospitfires.jpg
    * nextfile.jpg
    * etc.gif

Re: Removing unwanted and hidden files in a directory list

If you have an exact list of things to remove, you can do:

@filename_list =  Dir.entries("#{RAILS_ROOT}/public" + @filename_dir) - ['..', '.']

Another approach is to select only filenames that don't start with a period:
@filename_list =  Dir.entries("#{RAILS_ROOT}/public" + @filename_dir).select do |filename|
  filename[0].chr != '.'
end

Vincent Woo Ruby on Rails Blog

Re: Removing unwanted and hidden files in a directory list

You can use the "reject" method.

@filename_list.reject! { |filename| filename.starts_with? '.' }

Railscasts - Free Ruby on Rails Screencasts

Re: Removing unwanted and hidden files in a directory list

Thanks guys. Each of those do the trick - Ryan's if I want it in the view, and Vwoo's if I want it in the controller.

Also, how do you guys know something like that so quickly. I was searching all over the web, and do not really know how to navigate the api very well yet. Is there a recommended resource to search for answers to problems like this or is there a method to searching the api?

Last edited by scottmotte (2007-07-06 20:06:39)

Re: Removing unwanted and hidden files in a directory list

I recommend using my approach in the controller as well. It is too complicated to have in the view.

scottmotte wrote:

Also, how do you guys know something like that so quickly. I was searching all over the web, and do not really know how to navigate the api very well yet. Is there a recommended resource to search for answers to problems like this or is there a method to searching the api?

You need to get familiar with the Array methods. Go through each method and try using it in script/console or irb. It is definitely worth learning.

Railscasts - Free Ruby on Rails Screencasts

Re: Removing unwanted and hidden files in a directory list

Ok Ryan. I see now how I can put yours in the controller as well.

Thanks again for your help and thanks for the tip on going through the array methods in irb. I will do that.

Last edited by scottmotte (2007-07-07 12:17:39)