Rails - Creating temp files in a portable way

ⅰ亾dé卋堺 提交于 2019-12-02 20:18:35

tmp/ is definitively the right place to put the files.

The best way I've found of creating files on that folder is using ruby's tempfile library.

The code looks like this:

require 'tempfile'

def foo()
  # creates a temporary file in tmp/
  Tempfile.open('prefix', Rails.root.join('tmp') ) do |f|
    f.print('a temp message')
    f.flush
    #... do more stuff with f
  end
end

I like this solution because:

  • It generates random file names automatically (you can provide a prefix)
  • It automatically deletes the files when they are no longer used. For example, if invoked on a rake task, the files are removed when the rake task ends.

Rails apps also have their own tmp/ directory. I guess that one is always available and thus a good candidate to use and keep your application portable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!