Method: Pathname#rename_extname

Defined in:
lib/pleasant_path/pathname.rb

#rename_extname(new_extname) ⇒ Pathname #rename_extname(new_extname) {|source, destination| ... } ⇒ Pathname

Changes the file extension (extname) of the file indicated by the Pathname, replacing any existing file or directory of the same resultant 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:

Replace extension

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

Pathname.new("dir/file.abc").rename_extname(".xyz")
  # == Pathname.new("dir/file.xyz")

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

Add extension

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

Pathname.new("dir/file").rename_extname(".abc")
  # == Pathname.new("dir/file.abc")

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

Remove extension

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

Pathname.new("dir/file.abc").rename_extname("")
  # == Pathname.new("dir/file")

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

With a block

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

Pathname.new("dir/file.abc").rename_extname(".xyz") do |source, destination|
  source                     # == Pathname.new("dir/file.abc")
  destination                # == Pathname.new("dir/file.xyz")
end                          # == Pathname.new("dir/file.xyz")

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

Overloads:

See Also:



925
926
927
# File 'lib/pleasant_path/pathname.rb', line 925

def rename_extname(new_extname, &block)
  self.move_as(self.sub_ext(new_extname), &block)
end