Methods

Files

Tins::SecureWrite

Public Instance Methods

secure_write(filename, content = nil, mode = 'w') click to toggle source

Write to a file atomically

# 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

[Validate]

Generated with the Darkfish Rdoc Generator 2.