Class: FileWriter
- Inherits:
-
Object
- Object
- FileWriter
- Defined in:
- lib/file_writer.rb,
lib/file_writer/version.rb
Overview
Overwrite files safely
Constant Summary collapse
- SPLIT_SIZE =
65536- VERSION =
"0.2.0"
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
58 59 60 |
# File 'lib/file_writer.rb', line 58 def self.write(fname, contents) FileWriter.new(fname).write(contents) end |
Instance Method Details
#write(contents) ⇒ Object
Overwrite the file
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/file_writer.rb', line 24 def write(contents) backup = fname + "~" existing = File.exists?(fname) if existing fmode = File.stat(fname).mode begin File.rename(fname, backup) rescue SystemCallError FileUtils.cp(fname,fname+"~") end else fmode = nil end File.open(fname, "wb+", fmode) do |f| size = contents.bytesize written = f.write(contents) if written != size raise SystemCallError.new("FileWriter#write: write returned unexpected length") end f.flush f.fsync end end |