class TestFriends::Tempfile

Public Class Methods

new(options = {}) click to toggle source
# File lib/test_friends/tempfile.rb, line 20
def initialize options = {}
  opt = { :extname => nil, :filename => nil, }.merge(options)
  dir = Dir.mktmpdir
  if opt[:filename] then
    file = create_tempfile_by_name dir, opt[:filename]
  elsif opt[:extname] then
    file = create_tempfile_with_extname dir, opt[:extname]
  else
    file = create_tempfile dir
  end
  ObjectSpace.define_finalizer self, Destructor.new(dir)
  @path = Pathname.new file.path
  @tempfile = file
  @dir = Pathname.new dir
end

Private Class Methods

destructor(path) click to toggle source
# File lib/test_friends/tempfile.rb, line 80
def Tempfile.destructor path
  proc { path.delete if path.exist? }
end

Public Instance Methods

teardown() click to toggle source
# File lib/test_friends/tempfile.rb, line 44
def teardown
  @tempfile.close!
  @dir.rmtree if @dir.exist?
  ObjectSpace.undefine_finalizer self
end
to_path() click to toggle source
# File lib/test_friends/tempfile.rb, line 36
def to_path
  @path
end
touch(mtime = Time.now, nocreate = false) click to toggle source
# File lib/test_friends/tempfile.rb, line 40
def touch mtime = Time.now, nocreate = false
  FileUtils.touch self.to_s, { :mtime => mtime, :nocreate => nocreate }
end

Private Instance Methods

behave_like_tempfile(path) click to toggle source
# File lib/test_friends/tempfile.rb, line 66
def behave_like_tempfile path
  ObjectSpace.define_finalizer path, Tempfile.destructor(path)
  class << path
    def path
      self.to_path
    end

    def close!
      self.delete if self.exist?
      ObjectSpace.undefine_finalizer self
    end
  end
end
create_tempfile(tmpdir) click to toggle source
# File lib/test_friends/tempfile.rb, line 51
def create_tempfile tmpdir
  ::Tempfile.new('', tmpdir)
end
create_tempfile_by_name(tmpdir, filename) click to toggle source
# File lib/test_friends/tempfile.rb, line 55
def create_tempfile_by_name tmpdir, filename
  new_file = Pathname.new(tmpdir) + filename
  FileUtils.touch new_file.to_s
  behave_like_tempfile new_file
  new_file
end
create_tempfile_with_extname(tmpdir, extname) click to toggle source
# File lib/test_friends/tempfile.rb, line 62
def create_tempfile_with_extname tmpdir, extname
  ::Tempfile.new([nil, extname], tmpdir)
end