Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Better File.find (See related posts)

Better File.find

=begin File.find by c00lryguy
  Find all files in given path
  extension and filename optional
  
  File.find(path, ext, filename)
  
  Can also use hash as arguments:
    File.find(:path=>"C:\\",   <= ending backslash optional
              :ext=>".ini",    <= beginning period optional
              :filename=>"foo")
              
  Examples:
  
  File.find("E:\\") => all files on E:\
  File.find(:path=>"E:\\",:ext=>"rb") => all .rb files in E:\
  File.find("E:\\", ".rb", "foo") => all files named foo.rb in E:\
  
  Can also use multiple filenames and extensions:
  
  File.find(:path=>"E:\\",
            :ext=>[".ini", ".rb"],
            :filename=>["foo", bar]) => all files named foo or bar with either .ini or .rb extensions
=end

class File
  class << self
    def find(*args)
      require 'ostruct'
      
      input_query, filelist = {}, []
      
      #parse arguments
      if args.length == 1 && args[0].class == Hash
        input_query = args[0]
      elsif args.length >= 1
        if args.length > 3 : raise("Too many arguments\nCorrect arguments: path, ext, filename\n") end
        input_query[:path] = 
        input_query[:ext] = args[1] if args[1]
        input_query[:filename] = args[2] if args[2]
      end
      
      query = OpenStruct.new({:path=>nil, :ext=>"*", :filename=>"*"}.merge(input_query)) #creates query.path, query.ext, and query.filename
      if query.path == nil : raise("Argument 'path' not given") end
      
      
      query.ext.to_a.each{ |e|
        e[/\A\./] ? e=e[1..e.length-1] : e=e  #remove beginning periond on each ext if exists
        query.filename.to_a.each{ |f|
          query.path[/\\\z/] ? query.path=query.path[0..query.path.length-2] : query.path=query.path  #remove end backslash on path if exists
          filelist = filelist + Dir[ File.join(query.path.split(/\\/), "**", "#{f}.#{e}") ]
        }
      }
      
      return filelist
    end
  end
end

Comments on this post

djberg96 posts on May 18, 2008 at 01:27
See my file-find library. :)

You need to create an account or log in to post comments to this site.


Click here to browse all 7297 code snippets

Related Posts