Class: I18nContextGenerator::Writers::AtomicFile
- Inherits:
-
Object
- Object
- I18nContextGenerator::Writers::AtomicFile
- Defined in:
- lib/i18n_context_generator/writers/atomic_file.rb
Overview
Safely replaces an existing file after optionally validating the candidate.
Class Method Summary collapse
Class Method Details
.replace(path, content) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/i18n_context_generator/writers/atomic_file.rb', line 11 def replace(path, content) original_mode = File.stat(path).mode & 0o7777 directory = File.dirname(File.(path)) basename = File.basename(path) temporary_file = Tempfile.new([".#{basename}.", '.tmp'], directory) temporary_path = temporary_file.path begin temporary_file.binmode temporary_file.write(content) temporary_file.flush temporary_file.fsync temporary_file.chmod(original_mode) temporary_file.close yield temporary_path if block_given? File.rename(temporary_path, path) ensure temporary_file.close unless temporary_file.closed? FileUtils.rm_f(temporary_path) end end |