diff --git a/lib/find.rb b/lib/find.rb index 571609c..b21146f 100644 --- a/lib/find.rb +++ b/lib/find.rb @@ -64,6 +64,17 @@ module Find end # + # Recursively iterates over every file and directory listed as arguments, + # calling the associated block with the name of every file encountered. + # + # Returns an enumerator if no block is given. + # + def each_file(*paths) # :yield: path + block_given? or return enum_for(__method__, *paths) + self.find(*paths){|f| yield f if File.file? f } + end + + # # Skips the current file or directory, restarting the loop with the next # entry. If the current file is a directory, that directory will not be # recursively entered. Meaningful only within the block associated with @@ -75,5 +86,5 @@ module Find throw :prune end - module_function :find, :prune + module_function :find, :each_file, :prune end diff --git a/test/test_find.rb b/test/test_find.rb index f6e7f7a..d16c9ad 100644 --- a/test/test_find.rb +++ b/test/test_find.rb @@ -210,6 +210,33 @@ class TestFind < Test::Unit::TestCase } end + def test_each_file + Dir.mktmpdir {|d| + File.open("#{d}/a", "w"){} + Dir.mkdir("#{d}/b") + File.open("#{d}/b/a", "w"){} + File.open("#{d}/b/b", "w"){} + Dir.mkdir("#{d}/c") + a = [] + Find.each_file(d) {|f| a << f } + assert_equal(["#{d}/a", "#{d}/b/a", "#{d}/b/b"], a) + } + end + + def test_each_file_enumerator + Dir.mktmpdir {|d| + File.open("#{d}/a", "w"){} + Dir.mkdir("#{d}/b") + File.open("#{d}/b/a", "w"){} + File.open("#{d}/b/b", "w"){} + Dir.mkdir("#{d}/c") + e = Find.each_file(d) + a = [] + e.each {|f| a << f } + assert_equal(["#{d}/a", "#{d}/b/a", "#{d}/b/b"], a) + } + end + class TestInclude < Test::Unit::TestCase include Find