Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created August 12, 2022 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/76e6782ad8653e3ec7be0b92f0d3dc34 to your computer and use it in GitHub Desktop.
Save havenwood/76e6782ad8653e3ec7be0b92f0d3dc34 to your computer and use it in GitHub Desktop.
Example of atomic move for #ruby IRC
require 'fileutils'
require 'tempfile'
def write_atomically(content, temp_name: 'temp.txt', atomic_path: 'atomic.txt')
temp = Tempfile.new temp_name
temp.write content
temp.close
FileUtils.mv temp.path, atomic_path
ensure
temp.unlink
end
write_atomically 'foo'
write_atomically 'bar'
p File.read 'atomic.txt'
#=> "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment