Rails - 以可移植的方式创建临时文件 [英] Rails - Creating temp files in a portable way
问题描述
我的 rails 应用程序在 Ubuntu 服务器机器上运行.
My rails application runs on a Ubuntu server machine.
我需要创建临时文件,以便将它们馈送"到第二个独立的应用程序(我将为此使用 rake 任务,以防需要此信息)
I need to create temporary files in order to "feed" them to a second, independent app (I'll be using rake tasks for this, in case this information is needed)
我的问题是:在 Rails 应用程序上创建临时字段的最佳方法是什么?
My question is: what is the best way of creating temporary fields on a rails application?
因为我在 ubuntu,所以我可以在 /tmp/whatever
上创建它们,但是什么只能在 linux 中工作.
Since I'm in ubuntu, I could create them on /tmp/whatever
, but what would work only in linux.
我希望我的应用程序尽可能具有便携性 - 这样它就可以安装在 Windows 机器上&mac,如果需要.
I'd like my application to be as portable as possible - so it can be installed on Windows machines & mac, if needed.
有什么想法吗?
非常感谢.
推荐答案
tmp/
绝对是放置文件的正确位置.
tmp/
is definitively the right place to put the files.
我发现在该文件夹上创建文件的最佳方法是使用 ruby 的临时文件库.
The best way I've found of creating files on that folder is using ruby's tempfile library.
代码如下:
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:
- 它会自动生成随机文件名(您可以提供前缀)
- 当不再使用文件时,它会自动删除文件.例如,如果在 rake 任务上调用,则在 rake 任务结束时删除文件.
这篇关于Rails - 以可移植的方式创建临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!