跳到內容 跳到搜尋
方法
A

類別公開方法

atomic_write(file_name, temp_dir = dirname(file_name))

以原子方式寫入檔案。適用於不希望其他程序或執行緒看到半寫入檔案的情況。

File.atomic_write('important.file') do |file|
  file.write('hello')
end

此方法需要建立暫存檔。預設會在與目標檔案相同的目錄中建立。如果您不喜歡此行為,您可以提供不同的目錄,但它必須與您嘗試寫入的檔案位於相同的實體檔案系統上。

File.atomic_write('/data/something.important', '/data/tmp') do |file|
  file.write('hello')
end
# File activesupport/lib/active_support/core_ext/file/atomic.rb, line 21
def self.atomic_write(file_name, temp_dir = dirname(file_name))
  require "tempfile" unless defined?(Tempfile)

  Tempfile.open(".#{basename(file_name)}", temp_dir) do |temp_file|
    temp_file.binmode
    return_val = yield temp_file
    temp_file.close

    old_stat = if exist?(file_name)
      # Get original file permissions
      stat(file_name)
    else
      # If not possible, probe which are the default permissions in the
      # destination directory.
      probe_stat_in(dirname(file_name))
    end

    if old_stat
      # Set correct permissions on new file
      begin
        chown(old_stat.uid, old_stat.gid, temp_file.path)
        # This operation will affect filesystem ACL's
        chmod(old_stat.mode, temp_file.path)
      rescue Errno::EPERM, Errno::EACCES
        # Changing file ownership failed, moving on.
      end
    end

    # Overwrite original file with temp file
    rename(temp_file.path, file_name)
    return_val
  end
end