Sha256: b83e5781d393aa27efdee7504a555c2e2d5e0f1a9a290e41bbe3416698cfdba8

Contents?: true

Size: 681 Bytes

Versions: 7

Compression:

Stored size: 681 Bytes

Contents

module Tins
  module SecureWrite
    # Write to a file atomically
    def secure_write(filename, content = nil, mode = 'w')
      temp = File.new(filename.to_s + ".tmp.#$$.#{Time.now.to_f}", mode)
      if content.nil? and block_given?
        yield temp
      elsif !content.nil?
        temp.write content
      else
        raise ArgumentError, "either content or block argument required"
      end
      temp.fsync
      size = temp.stat.size
      temp.close
      File.rename temp.path, filename
      size
    ensure
      if temp
        !temp.closed? and temp.close
        File.file?(temp.path) and File.unlink temp.path
      end
    end
  end
end

require 'tins/alias'

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
tins-1.38.0 lib/tins/secure_write.rb
tins-1.37.1 lib/tins/secure_write.rb
tins-1.37.0 lib/tins/secure_write.rb
tins-1.36.1 lib/tins/secure_write.rb
tins-1.36.0 lib/tins/secure_write.rb
tins-1.35.0 lib/tins/secure_write.rb
tins-1.34.0 lib/tins/secure_write.rb