Created
October 19, 2011 15:57
-
-
Save mort/1298739 to your computer and use it in GitHub Desktop.
A very basic but flexible approach to performing tasks on files and folders by invoking a callback object rather than acting directly on them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Doing a crawl, passing a Doer class and a couple of regexp to filter out the filenames | |
require 'crawler' | |
crawler = Crawler.new('/Users/mort/Documents', Doer, :patterns => [/foo/, /karma/]) | |
crawler.crawl | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Crawler | |
# Goes through each file and folder inside the base folder and calls the 'do' method on a 'doer' callback object, passing the file/folder as a parameter | |
# Options: | |
# :skip_folders, :skip_files (boolean) for doing just that | |
# :ignore_hidden (boolean) for ignoring hidden files | |
# :patterns an array of regexps. Dir/files will only be passed to the doer object if its name match at least one of the regexps | |
require 'doers' | |
attr_reader :base | |
def initialize(base, callback = nil, options = {}) | |
@base = base | |
@callback = callback | |
@options = options | |
end | |
def crawl_dir(dir) | |
raise "Boom" unless File.directory?(dir) | |
skip_folders = @options.delete(:skip_folders) | |
skip_files = @options.delete(:skip_files) | |
ignore_hidden = @options.delete(:ignore_hidden) || true | |
patterns = @options.delete(:patterns) | |
Dir.foreach(dir) do |f| | |
ok = true | |
next if ['.','..'].include?(f) | |
next if f.match(/^\..*$/) if ignore_hidden | |
if patterns.is_a?(Array) && !patterns.empty? | |
ok = false | |
patterns.each do |p| | |
ok = true if !p.match(f).nil? | |
end | |
next unless ok | |
end | |
c = File.join(dir,f) | |
if File.directory?(c) | |
@callback.send(:do, c) unless skip_folders | |
crawl_dir(c) | |
else | |
@callback.send(:do, c) unless skip_files | |
end | |
end | |
end | |
def crawl | |
crawl_dir(@base) | |
end | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# An almost blank 'doer' class | |
class Doer | |
def self.do(file) | |
return unless File.exists?(file) | |
if File.directory?(file) | |
puts "Directory: #{file}" | |
else | |
puts " -- #{file}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment