Method: Pathname#rename_basename

Defined in:
lib/pleasant_path/pathname.rb

#rename_basename(new_basename) ⇒ Pathname #rename_basename(new_basename) {|source, destination| ... } ⇒ Pathname

Renames the file or directory indicated by the Pathname relative to its dirname, replacing any existing file or directory of the same basename.

If a block is given and a file or directory does exist at the resultant destination, the block is called with the source and destination Pathnames, and the return value of the block is used as the new destination. If the block returns the source Pathname or nil, the rename is aborted.

Returns the destination as a Pathname (or the source Pathname in the case that the rename is aborted).

WARNING: Due to system API limitations, the rename is performed in two steps, non-atomically. First, any file or directory existing at the destination is deleted. Next, the source is moved to the destination. The second step can fail independently of the first, e.g. due to insufficient disk space, leaving the file or directory previously at the destination deleted without replacement.

Examples:

Without a block

FileUtils.mkpath("dir")
FileUtils.touch("dir/file")

Pathname.new("dir/file").rename_basename("same_file")
  # == Pathname.new("dir/same_file")

File.exist?("dir/file")       # == false
File.exist?("dir/same_file")  # == true

With a block

FileUtils.mkpath("dir")
FileUtils.touch("dir/file1")
FileUtils.touch("dir/file2")

Pathname.new("dir/file1").rename_basename("file2") do |source, destination|
  source                  # == Pathname.new("dir/file1")
  destination             # == Pathname.new("dir/file2")
end                       # == Pathname.new("dir/file2")

File.exist?("dir/file1")  # == false
File.exist?("dir/file2")  # == true

Overloads:

See Also:



846
847
848
# File 'lib/pleasant_path/pathname.rb', line 846

def rename_basename(new_basename, &block)
  self.move_as(self.dirname / new_basename, &block)
end