Class: FilePathGenerator
- Inherits:
-
Object
- Object
- FilePathGenerator
- Defined in:
- lib/path_for_new_file.rb
Instance Method Summary collapse
- #increment_dir_counter(dir_depth = 0) ⇒ Object
- #indent_dirs ⇒ Object
-
#initialize(max_entries_per_dir = 10_000) ⇒ FilePathGenerator
constructor
A new instance of FilePathGenerator.
- #path_for_new_file(file_name) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(max_entries_per_dir = 10_000) ⇒ FilePathGenerator
Returns a new instance of FilePathGenerator.
2 3 4 5 6 |
# File 'lib/path_for_new_file.rb', line 2 def initialize(max_entries_per_dir = 10_000) @max_entries_per_dir = max_entries_per_dir @entry_counts = [0] @dir_mask = "%0#{max_entries_per_dir.to_s.length}d" end |
Instance Method Details
#increment_dir_counter(dir_depth = 0) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/path_for_new_file.rb', line 18 def increment_dir_counter(dir_depth = 0) if dir_depth > (@entry_counts.size - 1) @entry_counts << 2 indent_dirs return end @entry_counts[dir_depth] += 1 if @entry_counts[dir_depth] > @max_entries_per_dir @entry_counts[dir_depth] = 1 increment_dir_counter(dir_depth + 1) end end |
#indent_dirs ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/path_for_new_file.rb', line 34 def indent_dirs tmp_dir_name = "tmp_#{@entry_counts.size}" FileUtils.mkdir tmp_dir_name Dir.entries(".").each do |existing_dir| next if existing_dir =~ %r(\.\.?) next if existing_dir == tmp_dir_name FileUtils.mv existing_dir, tmp_dir_name end new_dir_name = @dir_mask % [0] FileUtils.mv tmp_dir_name, new_dir_name end |
#path_for_new_file(file_name) ⇒ Object
8 9 10 11 12 13 14 15 16 |
# File 'lib/path_for_new_file.rb', line 8 def path_for_new_file(file_name) increment_dir_counter return file_name if @entry_counts.size == 1 dir_paths = @entry_counts[1..-1].reverse.map{|n| @dir_mask % [n - 1] } dir_path = File.join(".", *dir_paths) FileUtils.mkdir_p(dir_path) File.join(dir_path, file_name) end |
#to_s ⇒ Object
46 47 48 |
# File 'lib/path_for_new_file.rb', line 46 def to_s "[ #{@entry_counts.join(',')} ]" end |