Module: ZipKit::UniquifyFilename
- Defined in:
- lib/zip_kit/uniquify_filename.rb
Class Method Summary collapse
-
.call(path, while_included_in) ⇒ String
Makes a given filename unique by appending a (n) suffix between just before the filename extension.
Class Method Details
.call(path, while_included_in) ⇒ String
Makes a given filename unique by appending a (n) suffix
between just before the filename extension. So "file.txt" gets
transformed into "file (1).txt". The transformation is applied
repeatedly as long as the generated filename is present
in while_included_in
object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/zip_kit/uniquify_filename.rb', line 13 def self.call(path, while_included_in) return path unless while_included_in.include?(path) # we add (1), (2), (n) at the end of a filename before the filename extension, # but only if there is a duplicate copy_pattern = /\((\d+)\)$/ parts = path.split(".") ext = if parts.last =~ /gz|zip/ && parts.size > 2 parts.pop(2) elsif parts.size > 1 parts.pop end fn_last_part = parts.pop duplicate_counter = 1 loop do fn_last_part = if fn_last_part&.match?(copy_pattern) fn_last_part.sub(copy_pattern, "(#{duplicate_counter})") else "#{fn_last_part} (#{duplicate_counter})" end new_path = (parts + [fn_last_part, ext]).compact.join(".") return new_path unless while_included_in.include?(new_path) duplicate_counter += 1 end end |