Class: Graphomaton::AtomicFile

Inherits:
Object
  • Object
show all
Defined in:
lib/graphomaton/atomic_file.rb

Class Method Summary collapse

Class Method Details

.write(filename, content, binary: false) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/graphomaton/atomic_file.rb', line 7

def self.write(filename, content, binary: false)
  destination = File.expand_path(filename)
  directory = File.dirname(destination)
  basename = File.basename(destination)
  existing_mode = File.stat(destination).mode & 0o7777 if File.exist?(destination)

  Tempfile.create([".#{basename}", '.tmp'], directory, binmode: binary) do |temporary|
    temporary.binmode if binary
    temporary.chmod(existing_mode) if existing_mode
    temporary.write(content)
    temporary.flush
    temporary.fsync
    temporary.close
    File.rename(temporary.path, destination)
  end

  content.bytesize
end