Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activesupport/lib/active_support/core_ext/file.rb

Revision 9093, 0.7 kB (checked in by pratik, 7 months ago)

Improve documentation.

Line 
1 require 'tempfile'
2
3 # Write to a file atomically.  Useful for situations where you don't
4 # want other processes or threads to see half-written files.
5 #
6 #   File.atomic_write("important.file") do |file|
7 #     file.write("hello")
8 #   end
9 #
10 # If your temp directory is not on the same filesystem as the file you're
11 # trying to write, you can provide a different temporary directory.
12 #
13 #   File.atomic_write("/data/something.important", "/data/tmp") do |f|
14 #     file.write("hello")
15 #   end
16 def File.atomic_write(file_name, temp_dir = Dir.tmpdir)
17   temp_file = Tempfile.new(File.basename(file_name), temp_dir)
18   yield temp_file
19   temp_file.close
20   File.rename(temp_file.path, file_name)
21 end
Note: See TracBrowser for help on using the browser.