Created
March 5, 2009 21:23
-
-
Save dcparker/74560 to your computer and use it in GitHub Desktop.
File tree crawler example.
This file contains 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
#!/usr/bin/ruby | |
class WalkDirTree | |
def each_file(&block) | |
raise ArgumentError unless block_given? | |
@each_file = block | |
end | |
def walk!(dir='.') | |
current_directory = Dir.pwd | |
Dir.chdir(dir) | |
Dir.glob('*').each do |f| | |
if File.directory?(f) | |
walk!(f) | |
else | |
if @each_file | |
@each_file.call(current_directory + '/' + dir + '/' + f) | |
end | |
end | |
end | |
Dir.chdir(current_directory) | |
end | |
end | |
# Example usage: translate CRLF's to just LF! | |
walker = WalkDirTree.new | |
walker.each_file do |filename| | |
file = File.read(filename) | |
File.open(filename, 'w') do |fh| | |
fh.write(file.gsub(/\r?\n/,"\n")) | |
end | |
end | |
walker.walk! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment