Sha256: 54f28302e29c701cbb3262928a3c967a4d49a9fb4a6942f16207d009b694b280

Contents?: true

Size: 967 Bytes

Versions: 1

Compression:

Stored size: 967 Bytes

Contents

# frozen_string_literal: true

require 'atomos/version'

module Atomos
  module_function

  def atomic_write(dest, contents = nil, tmpdir: nil, &block)
    unless contents.nil? ^ block.nil?
      raise ArgumentError, 'must provide either contents or a block'
    end

    tmpdir = Atomos.default_tmpdir_for_file(dest, tmpdir)

    require 'tempfile'
    Tempfile.open(".atomos.#{File.basename(dest)}", tmpdir) do |tmpfile|
      if contents
        tmpfile << contents
      else
        retval = yield tmpfile
      end

      File.rename(tmpfile.path, dest)

      retval
    end
  end

  def self.default_tmpdir_for_file(dest, tmpdir)
    tmpdir ||= begin
      require 'tmpdir'
      Dir.tmpdir
    end

    # Ensure the destination is on the same device as tmpdir
    if File.stat(tmpdir).dev != File.stat(File.dirname(dest)).dev
      # If not, use the directory of the destination as the tmpdir.
      tmpdir = File.dirname(dest)
    end

    tmpdir
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
atomos-0.1.2 lib/atomos.rb