class FileWriter

Overwrite files safely

Constants

VERSION

Attributes

fname[R]

The filename of the file to overwrite

Public Class Methods

new(fname) click to toggle source

Create new FileWriter

@param String fname The name of he file to overwrite

# File lib/file_writer.rb, line 14
def initialize(fname)
  @fname = fname
end
write(fname, contents) click to toggle source

Overwrite the file

@param String fname The name of the file to overwrite @param String contents The new contents for the file.

# File lib/file_writer.rb, line 52
def self.write(fname, contents)
  FileWriter.new(fname).write(contents)
end

Public Instance Methods

write(contents) click to toggle source

Overwrite the file

@param String contents The new contents for the file.

# File lib/file_writer.rb, line 22
def write(contents)
  backup = fname + "~"

  existing = File.exists?(fname)

  if existing
    mode   = File.stat(fname).mode
    begin
      File.rename(fname, backup)
    rescue SystemCallError
      FileUtils.cp(fname,fname+"~")
    end
  else
    mode = nil
  end

  File.open(fname, "wb+", mode) do |f|
    if f.syswrite(contents) != contents.bytesize
      raise SystemCallError.new("FileWriter#write: syswrite returned unexpected length")
    end
    f.flush
    f.fsync
  end
end