Class: FileWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/file_writer.rb,
lib/file_writer/version.rb

Overview

Overwrite files safely

Constant Summary collapse

VERSION =
"0.1.2"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fname) ⇒ FileWriter

Create new FileWriter

Parameters:

  • String

    fname The name of he file to overwrite



14
15
16
# File 'lib/file_writer.rb', line 14

def initialize(fname)
  @fname = fname
end

Instance Attribute Details

#fnameObject (readonly)

The filename of the file to overwrite



9
10
11
# File 'lib/file_writer.rb', line 9

def fname
  @fname
end

Class Method Details

.write(fname, contents) ⇒ Object

Overwrite the file

Parameters:

  • String

    fname The name of the file to overwrite

  • String

    contents The new contents for the file.



52
53
54
# File 'lib/file_writer.rb', line 52

def self.write(fname, contents)
  FileWriter.new(fname).write(contents)
end

Instance Method Details

#write(contents) ⇒ Object

Overwrite the file

Parameters:

  • String

    contents The new contents for the file.



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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