tempfile-open2.patch

Akira Tanaka, 12/04/2011 11:31 PM

Download (1.52 KB)

View differences:

lib/tempfile.rb (working copy)
321 321
  end
322 322
end
323 323

  
324
# Creates a temporally file as usual File object (not Tempfile).
325
# It don't use finalizer and delegation.
326
#
327
# If no block is given, this is similar to Tempfile.new except
328
# creating File instead of Tempfile.
329
# The created file is not removed automatically.
330
# You should use File.unlink to remove it.
331
#
332
# If a block is given, then a File object will be constructed,
333
# and the block is run with said object as argument.
334
# The File object will be automatically closed and
335
# the temporally file is removed after the block terminates.
336
# The call returns the value of the block.
337
#
338
# In any case, all arguments (+*args+) will be treated as Tempfile.new.
339
#
340
#   Tempfile.open2('foo', '/home/temp') do |f|
341
#      ... do something with f ...
342
#   end
343
#
344
def Tempfile.open2(basename, *rest)
345
  tmpfile = nil
346
  Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts|
347
    mode = File::RDWR|File::CREAT|File::EXCL
348
    perm = 0600
349
    if opts
350
      mode |= opts.delete(:mode) || 0
351
      opts[:perm] = perm
352
      perm = nil
353
    else
354
      opts = perm
355
    end
356
    tmpfile = File.open(tmpname, mode, opts)
357
  end
358
  if block_given?
359
    begin
360
      yield tmpfile
361
    ensure
362
      File.unlink tmpfile
363
    end
364
  else
365
    tmpfile
366
  end
367
end
368

  
324 369
if __FILE__ == $0
325 370
#  $DEBUG = true
326 371
  f = Tempfile.new("foo")