Class: FileWriter
- Inherits:
-
Object
- Object
- FileWriter
- 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
-
#fname ⇒ Object
readonly
The filename of the file to overwrite.
Class Method Summary collapse
-
.write(fname, contents) ⇒ Object
Overwrite the file.
Instance Method Summary collapse
-
#initialize(fname) ⇒ FileWriter
constructor
Create new FileWriter.
-
#write(contents) ⇒ Object
Overwrite the file.
Constructor Details
#initialize(fname) ⇒ FileWriter
Create new FileWriter
14 15 16 |
# File 'lib/file_writer.rb', line 14 def initialize(fname) @fname = fname end |
Instance Attribute Details
#fname ⇒ Object (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
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
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 |