son*_*gyy 6 ruby ruby-on-rails
我糊涂了.这是我的代码:
require 'csv'
require 'tempfile'
f = Tempfile.new('csv','/tmp')
f.write 'just wanna test'
f.close
p f.path
Run Code Online (Sandbox Code Playgroud)
如果我打开输出路径,它是空的.
我想这是因为每次ruby会话退出时,TempFile都会自动从文件系统中删除.但是,如何确切地知道文件何时被删除?因为我想用它在我的rails应用程序中创建临时文件,我担心如果文件在使用之前被删除了.
Ama*_*dan 12
来自docs:
当Tempfile对象被垃圾收集时,或者当Ruby解释器退出时,其关联的临时文件将被自动删除.
因此,只要您拥有自己f的范围,就不会删除它.如果退出Ruby,它将被删除.如果你仍然在Ruby中,但f已超出范围,则它是不确定的(可能没有删除,但不保证存在,不应该使用.)
Tempfile当我创建许多要压缩的临时文件时,我已经看到在同一过程中被垃圾收集。在下面的代码中,如果我没有将Tempfile句柄存储在handles数组中,我会Errno::ENOENT: No such file or directory @ rb_sysopen在Zip::File.open块关闭时收到运行时错误 ( ) :
handles = []
Zip::File.open(zip_file.path, Zip::File::CREATE) do |zip|
# there are hundreds of @foos to iterate over
@foos.each do |foo|
cit_filename = generate_some_unique_filename
cit_file = Tempfile.new(cit_filename)
handles << cit_file
cit_file.puts('some text')
cit_file.close
zip.add(cit_filename, cit_file.path)
end
end # <- runtime error would have thrown at this point
handles = nil
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4686 次 |
| 最近记录: |