Skip to content

Instantly share code, notes, and snippets.

@mrkn
Created Apr 21, 2011
Embed
What would you like to do?
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
index 8bdf086..fbe0e7d 100644
--- a/lib/tempfile.rb
+++ b/lib/tempfile.rb
@@ -194,6 +194,15 @@ class Tempfile < DelegateClass(File)
ObjectSpace.undefine_finalizer(self)
end
+ def mv(destination_path)
+ raise TypeError, "unlinked Tempfile" unless self.path
+ raise ArgumentError, "cannot move to the same path" if destination_path == self.path
+ _close
+ File.rename(self.path, destination_path)
+ unlink
+ ObjectSpace.undefine_finalizer(self)
+ end
+
# Unlinks (deletes) the file from the filesystem. One should always unlink
# the file after using it, as is explained in the "Explicit close" good
# practice section in the Tempfile overview:
diff --git a/test/test_tempfile.rb b/test/test_tempfile.rb
index 1462a98..000cd2d 100644
--- a/test/test_tempfile.rb
+++ b/test/test_tempfile.rb
@@ -63,6 +63,25 @@ class TestTempfile < Test::Unit::TestCase
assert_match(/\.txt$/, File.basename(t.path))
end
+ def test_mv
+ t = tempfile("foo")
+ path = t.path
+
+ assert_raise ArgumentError do
+ t.mv(path)
+ end
+
+ dest_path = File.expand_path("../bar", File.dirname(path))
+ begin
+ t.mv(dest_path)
+ assert !File.exist?(path)
+ assert_nil t.path
+ assert File.exist?(dest_path)
+ ensure
+ File.unlink(dest_path) if File.exist?(dest_path)
+ end
+ end
+
def test_unlink
t = tempfile("foo")
path = t.path
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
index 8bdf086..8d45c3d 100644
--- a/lib/tempfile.rb
+++ b/lib/tempfile.rb
@@ -194,6 +194,14 @@ class Tempfile < DelegateClass(File)
ObjectSpace.undefine_finalizer(self)
end
+ def mv(destination_path)
+ raise TypeError, "unlinked Tempfile" unless self.path
+ _close
+ File.rename(self.path, destination_path)
+ unlink
+ ObjectSpace.undefine_finalizer(self)
+ end
+
# Unlinks (deletes) the file from the filesystem. One should always unlink
# the file after using it, as is explained in the "Explicit close" good
# practice section in the Tempfile overview:
diff --git a/test/test_tempfile.rb b/test/test_tempfile.rb
index 1462a98..5c0d6bf 100644
--- a/test/test_tempfile.rb
+++ b/test/test_tempfile.rb
@@ -63,6 +63,21 @@ class TestTempfile < Test::Unit::TestCase
assert_match(/\.txt$/, File.basename(t.path))
end
+ def test_mv
+ t = tempfile("foo")
+ path = t.path
+
+ dest_path = File.expand_path("../bar", File.dirname(path))
+ begin
+ t.mv(dest_path)
+ assert !File.exist?(path)
+ assert_nil t.path
+ assert File.exist?(dest_path)
+ ensure
+ File.unlink(dest_path) if File.exist?(dest_path)
+ end
+ end
+
def test_unlink
t = tempfile("foo")
path = t.path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment