Class: Debugfile

Inherits:
File
  • Object
show all
Defined in:
lib/debugfile.rb

Overview

Synopsis

require 'debugfile'

file = Debugfile.new('for_debug', 'foo.txt')
file.path #=> e.g.: "/tmp/for_debug/20140226/e34d7899-09cf-4b46-8ef4-4f751f9ae649-foo.txt"
file.write "hello!"
file.rewind
file.read  #=> "hello!"
file.close

file = Debugfile.open('for_debug', 'foo.txt') {|f| f.write "Ruby!" }
file.open
file.read #=> "Ruby!"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(outdirname, outfilename, tempdir = Dir.tmpdir, opts = {}) ⇒ Debugfile

Returns a new instance of Debugfile.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/debugfile.rb', line 26

def initialize(outdirname, outfilename, tempdir=Dir.tmpdir, opts={})
  if block_given?
    warn "Debugfile.new doesn't call the given block."
  end

  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

  datedir = File.join(tempdir, outdirname, Time.now.strftime("%Y%m%d"))
  FileUtils.mkdir_p datedir if !FileTest.exist? datedir
  fulloutfilename = "#{SecureRandom.uuid}-#{outfilename}"
  @path = File.join(datedir, fulloutfilename)
  @debugfile = File.open(@path, mode, opts)
  @mode = mode & ~(File::CREAT|File::EXCL)
  perm or opts.freeze
  @opts = opts
  super @debugfile
end

Class Method Details

.open(*args) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/debugfile.rb', line 72

def open(*args)
  debugfile = new(*args)

  if block_given?
    begin
      yield debugfile
    ensure
      debugfile.close
    end
  else
    debugfile
  end
end

Instance Method Details

#closeObject



58
59
60
61
62
63
64
65
# File 'lib/debugfile.rb', line 58

def close
  File.unlink @debugfile if @debugfile.size == 0
  begin
    @debugfile.close
  ensure
    @debugfile = nil
  end
end

#inspectObject



67
68
69
# File 'lib/debugfile.rb', line 67

def inspect
  "#<#{self.class}:#{path}>"
end

#openObject



52
53
54
55
56
# File 'lib/debugfile.rb', line 52

def open
  @debugfile.close if @debugfile
  @debugfile = File.open(@path, @mode, @opts)
  __setobj__ @debugfile
end