Created
August 12, 2022 17:56
-
-
Save havenwood/76e6782ad8653e3ec7be0b92f0d3dc34 to your computer and use it in GitHub Desktop.
Example of atomic move for #ruby IRC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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