summaryrefslogtreecommitdiff
path: root/lib/tempfile.rb
diff options
context:
space:
mode:
authorakr <akr@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-04-20 13:50:47 +0000
committerakr <akr@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-04-20 13:50:47 +0000
commit5388fb64d991db9c094d1972176c4f5794e3555f (patch)
tree0726bc8b3386a51d3043d5f75d7a9ce33566f5d7 /lib/tempfile.rb
parent8c77e58b97465ebfef0d94497a5eecd78f5bef3c (diff)
* lib/tempfile.rb (Tempfile.create): New method.
The method name is proposed by Shugo Maeda. [ruby-dev:47220] [ruby-core:41478] [Feature #5707] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@40393 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/tempfile.rb')
-rw-r--r--lib/tempfile.rb45
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
index fe78391..fd334c1 100644
--- a/lib/tempfile.rb
+++ b/lib/tempfile.rb
@@ -332,6 +332,51 @@ class Tempfile < DelegateClass(File)
end
end
+# Creates a temporally file as usual File object (not Tempfile).
+# It don't use finalizer and delegation.
+#
+# If no block is given, this is similar to Tempfile.new except
+# creating File instead of Tempfile.
+# The created file is not removed automatically.
+# You should use File.unlink to remove it.
+#
+# If a block is given, then a File object will be constructed,
+# and the block is invoked with the object as the argument.
+# The File object will be automatically closed and
+# the temporally file is removed after the block terminates.
+# The call returns the value of the block.
+#
+# In any case, all arguments (+*args+) will be treated as Tempfile.new.
+#
+# Tempfile.create('foo', '/home/temp') do |f|
+# ... do something with f ...
+# end
+#
+def Tempfile.create(basename, *rest)
+ tmpfile = nil
+ Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts|
+ mode = File::RDWR|File::CREAT|File::EXCL
+ perm = 0600
+ if opts
+ mode |= opts.delete(:mode) || 0
+ opts[:perm] = perm
+ perm = nil
+ else
+ opts = perm
+ end
+ tmpfile = File.open(tmpname, mode, opts)
+ end
+ if block_given?
+ begin
+ yield tmpfile
+ ensure
+ File.unlink tmpfile
+ end
+ else
+ tmpfile
+ end
+end
+
if __FILE__ == $0
# $DEBUG = true
f = Tempfile.new("foo")