From 6f8620be1a7720f6338d20fbc8433c59f0dea007 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carl=20H=C3=B6rberg?= Date: Fri, 7 Jul 2023 00:24:51 +0200 Subject: [PATCH] File#rename Like File.rename, but updates the `@path` of the instance --- spec/std/file_spec.cr | 10 ++++++++++ src/file.cr | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/spec/std/file_spec.cr b/spec/std/file_spec.cr index ae3e7d7519cf..4dbe8e51b53a 100644 --- a/spec/std/file_spec.cr +++ b/spec/std/file_spec.cr @@ -604,6 +604,16 @@ describe "File" do end end end + + it "renames a File instance" do + with_tempfile("rename-source.txt", "rename-target.txt") do |source_path, target_path| + f = File.new(source_path, "w") + f.rename target_path + f.path.should eq target_path + File.exists?(source_path).should be_false + File.exists?(target_path).should be_true + end + end end # There are more detailed specs for `Path#expand` in path_spec.cr diff --git a/src/file.cr b/src/file.cr index 8c363868f50e..19a62e6b630d 100644 --- a/src/file.cr +++ b/src/file.cr @@ -866,6 +866,12 @@ class File < IO::FileDescriptor end end + # Rename the current `File` + def rename(new_filename : Path | String) : Nil + File.rename(@path, new_filename) + @path = new_filename.to_s + end + # Sets the access and modification times of *filename*. # # Use `#utime` if the `File` is already open.