Project

General

Profile

Feature #3608 ยป lazy_path_test.rb

taw (Tomasz Wegrzanowski), 08/02/2010 05:43 AM

 
1
#!/usr/bin/env ruby1.9
2
# (ulimit -n 16; ./lazy_path_test.rb ~/src/ruby-trunk)
3

    
4
require 'pathname'
5
require "fileutils"
6

    
7
class Pathname
8
  def each_child(with_directory=true)
9
    block_given? or return enum_for(__method__, with_directory)
10
    with_directory = false if @path == '.'
11
    Dir.foreach(@path) {|e|
12
      next if e == '.' || e == '..'
13
      if with_directory
14
        yield self.class.new(File.join(@path, e))
15
      else
16
        yield self.class.new(e)
17
      end
18
    }
19
  end
20
  
21
  def find_files(&blk)
22
    if directory?
23
      each_child{|c| c.find_files(&blk) }
24
    else
25
      yield self
26
    end
27
  end
28
end
29

    
30
("00".."99").each{|d|
31
  FileUtils.mkdir_p d
32
  ("a".."z").each{|f| FileUtils.touch "#{d}/#{f}"}
33
}
34

    
35
puts "Ulimit is #{`ulimit -n`}" # As low as 16 works
36
root = Pathname(ARGV[0] || ".")
37

    
38
puts "Test 1" # Passes
39
root.each_child.select(&:directory?).map(&:each_child).each{|subdir| puts subdir.take(5) }
40

    
41
puts "Test 2" # Passes
42
root.find_files{|f| puts f}
43

    
44
puts "Test 3" # ./lazy_path_test.rb:45:in `open': Too many open files 
45
root.children.map{|d| Dir.open(d) if d.directory? }