Class: File

Inherits:
Object show all
Defined in:
lib/util/ruby_extensions.rb

Class Method Summary collapse

Class Method Details

.safe_write(dest, txt = nil, &block) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/util/ruby_extensions.rb', line 93

def File.safe_write(dest, txt=nil, &block)
  tmp = dest + "-" + rand(9999).to_s
  begin
    File.open(tmp, "w") do |file|
      if block
        block.call(file)
      elsif txt
        file.write(txt)
      end
    end
    FileUtils.mv(tmp, dest)
  rescue Exception
    FileUtils.remove_entry_secure(tmp)
    raise
  end
end