Rails - Creating temp files in a portable way

前端 未结 2 1556
情话喂你
情话喂你 2021-02-01 17:31

My rails application runs on a Ubuntu server machine.

I need to create temporary files in order to \"feed\" them to a second, independent app (I\'ll be using rake tasks

相关标签:
2条回答
  • 2021-02-01 17:43

    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.
    0 讨论(0)
  • 2021-02-01 18:00

    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.

    0 讨论(0)
提交回复
热议问题