Class: Kraps::TempPath

Inherits:
Object
  • Object
show all
Defined in:
lib/kraps/temp_path.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prefix: nil, suffix: nil) ⇒ TempPath

Returns a new instance of TempPath.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/kraps/temp_path.rb', line 5

def initialize(prefix: nil, suffix: nil)
  @path = File.join(Dir.tmpdir, [prefix, SecureRandom.hex[0, 16], Process.pid, suffix].compact.join("."))

  File.open(@path, File::CREAT | File::EXCL) {}

  ObjectSpace.define_finalizer(self, self.class.finalize(@path))

  return unless block_given?

  begin
    yield
  ensure
    unlink
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



3
4
5
# File 'lib/kraps/temp_path.rb', line 3

def path
  @path
end

Class Method Details

.finalize(path) ⇒ Object



25
26
27
# File 'lib/kraps/temp_path.rb', line 25

def self.finalize(path)
  proc { FileUtils.rm_f(path) }
end

Instance Method Details



21
22
23
# File 'lib/kraps/temp_path.rb', line 21

def unlink
  FileUtils.rm_f(@path)
end