Project

General

Profile

Feature #5707 » tempfile-open2.patch

akr (Akira Tanaka), 12/04/2011 11:31 PM

View differences:

lib/tempfile.rb (working copy)
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 run with said object as 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.open2('foo', '/home/temp') do |f|
# ... do something with f ...
# end
#
def Tempfile.open2(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")
(1-1/2)