Recursive Directory Scanner





8
Date Submitted Mon. Oct. 30th, 2006 12:17 AM
Revision 1 of 1
Scripter SCoon
Tags Directory | File | Ruby
Comments 0 comments
Customizable recursive directory scanner.
class DirectoryScanner

  def initialize
    @fileAction = nil
    @dirAction = nil
  end

  def on_file(&action)
    @fileAction = action
  end
 
  def on_dir(&action)
    @dirAction = action
  end
 
  def scan_subtree(parentPath)
    Dir.open(parentPath) { |dir|
      for file in dir
        next if file == '.';
        next if file == '..';
        path = parentPath + File::Separator + file
        if File.directory? path
          @dirAction.call(file, path) unless @dirAction.nil?
          scan_subtree(path)
        else
          @fileAction.call(file, path) unless @fileAction.nil?
        end
      end
    }
  end

end
scanner = DirectoryScanner.new
scanner.on_file { |file, path| puts "  #{file}" }
scanner.on_dir { |file, path| puts "#{path}" }
scanner.scan_subtree('c:/windows')

Vladislav Zlobin

Comments

There are currently no comments for this snippet.

Voting