Method: Pathname#available_name
- Defined in:
- lib/pleasant_path/pathname.rb
#available_name(format = "%{name}_%{i}%{ext}", i: 1) ⇒ Pathname
Finds an available name based on the Pathname. If the Pathname does not point to an existing file or directory, returns the Pathname. Otherwise, iteratively generates and tests names until one is found that does not point to an existing file or directory.
Names are generated using a Hash-style format string with three populated values:
-
%{name}: original Pathname basename without extname
-
%{ext}: original Pathname extname, including leading dot
-
%{i}: iteration counter; can be initialized via
:i
kwarg
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/pleasant_path/pathname.rb', line 399 def available_name(format = "%{name}_%{i}%{ext}", i: 1) return self unless self.exist? dirname = File.dirname(self) format = "%{dirname}/" + format unless dirname == "." values = { dirname: dirname, name: File.basename(self, ".*"), ext: self.extname, i: i, } while (path = format % values) && File.exist?(path) values[:i] += 1 end path.to_pathname end |