LoginSignup
1
0

More than 5 years have passed since last update.

tempfile をcopyを使わずに外に持っていく方法

Last updated at Posted at 2018-07-31

tempfile が巨大な場合、FileUtils.cp のコストが高い

たまによくあるこんなコード

require 'tempfile'
require 'fileutils'

Tempfile.create('hoge') do |tempfile|
  # ...
  # 処理が成功した場合は、result_file に tempfile の中身を入れたい
  FileUtils.cp(result_file, tempfile) if success?
end

解決案

FileUtils.ln を使えばコストは copy より軽くなる

  • ハードリンクなので、Tempfile.create ブロック終了時に tempfile が unlink されても result_file は削除されない
require 'tempfile'
require 'fileutils'

Tempfile.create('hoge') do |tempfile|
  # ...
  # 処理が成功した場合は、result_file に tempfile の中身を入れたい
  FileUtils.ln(result_file, tempfile) if success?
end

こういう場合のためのメソッドが欲しいというrubyのissueがあったけど、進捗はない様子

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0