| Module | ActiveSupport::CoreExtensions::File::Atomic |
| In: |
vendor/rails/activesupport/lib/active_support/core_ext/file/atomic.rb
|
Write to a file atomically. Useful for situations where you don‘t want other processes or threads to see half-written files.
File.atomic_write("important.file") do |file|
file.write("hello")
end
If your temp directory is not on the same filesystem as the file you‘re trying to write, you can provide a different temporary directory.
File.atomic_write("/data/something.important", "/data/tmp") do |f|
file.write("hello")
end
# File vendor/rails/activesupport/lib/active_support/core_ext/file/atomic.rb, line 18
18: def atomic_write(file_name, temp_dir = Dir.tmpdir)
19: require 'tempfile' unless defined?(Tempfile)
20:
21: temp_file = Tempfile.new(basename(file_name), temp_dir)
22: yield temp_file
23: temp_file.close
24:
25: begin
26: # Get original file permissions
27: old_stat = stat(file_name)
28: rescue Errno::ENOENT
29: # No old permissions, write a temp file to determine the defaults
30: check_name = join(dirname(file_name), ".permissions_check.#{Thread.current.object_id}.#{Process.pid}.#{rand(1000000)}")
31: open(check_name, "w") { }
32: old_stat = stat(check_name)
33: unlink(check_name)
34: end
35:
36: # Overwrite original file with temp file
37: rename(temp_file.path, file_name)
38:
39: # Set correct permissions on new file
40: chown(old_stat.uid, old_stat.gid, file_name)
41: chmod(old_stat.mode, file_name)
42: end