Module: Tins::SecureWrite

Included in:
IO
Defined in:
lib/tins/secure_write.rb

Instance Method Summary collapse

Instance Method Details

#secure_write(filename, content = nil, mode = 'w') ⇒ Object

Write to a file atomically



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/tins/secure_write.rb', line 4

def secure_write(filename, content = nil, mode = 'w')
  temp = File.new(filename + ".tmp.#$$.#{Time.now.to_f}", mode)
  if content.nil? and block_given?
    yield temp
  elsif !content.nil?
    temp.write content
  else
    raise ArgumentError, "either content or block argument required"
  end
  temp.fsync
  size = temp.stat.size
  temp.close
  File.rename temp.path, filename
  size
ensure
  if temp
    !temp.closed? and temp.close
    File.file?(temp.path) and File.unlink temp.path
  end
end