Ruby on rails 临时目录中的ruby临时文件

Ruby on rails 临时目录中的ruby临时文件,ruby-on-rails,Ruby On Rails,我想在临时目录中创建临时文件。下面是我的代码 require 'tmpdir' require 'tempfile' Dir.mktmpdir do |dir| Dir.chdir(dir) TemFile.new("f") sleep 20 end 这给了我一个例外: Errno::EACCES:权限被拒绝-C:/Users/S

我想在临时目录中创建临时文件。下面是我的代码

           require 'tmpdir'
           require 'tempfile'
           Dir.mktmpdir do |dir|
             Dir.chdir(dir)
             TemFile.new("f")
             sleep 20
           end
这给了我一个例外:
Errno::EACCES:权限被拒绝-C:/Users/SANJAY~1/AppData/Local/Temp/d20130724-5600-ka2ame
,因为ruby正在尝试删除一个临时目录,该目录不是空的

请帮助我在temp目录中创建一个temp文件。

您应该使用该类

require'tempfile'
file=Tempfile.new('foo')
file.path#=>操作系统临时目录中的唯一文件名,
#例如:“/tmp/foo.24722.0”
#此文件名的basename中包含“foo”。
file.write(“hello world”)
文件倒带
file.read#=>“你好,世界”
file.close
file.unlink#删除临时文件

要创建临时文件夹,可以使用。

嗨,我创建了前缀为“foo”的临时目录和前缀为cats的tempfile

dir = Dir.mktmpdir('foo')
begin      
  puts('Directory path:'+ dir) #Here im printing the path of the temporary directory

  # Creating the tempfile and giving as parameters the prefix 'cats' and 
  # the second parameter is the tempdirectory
  tempfile = Tempfile.new('cats', [tmpdir = dir]) 

  puts('File path:'+ tempfile.path)  #Here im printing the path of the tempfile
  tempfile.write("hello world")
  tempfile.rewind
  tempfile.read      # => "hello world"
  tempfile.close
  tempfile.unlink   
ensure
  # remove the directory.
  FileUtils.remove_entry dir
end
由于我们在控制台上打印路径,我们可以得到以下结果

Directory path: /tmp/foo20181116-9699-1o7jc6x
File path:  /tmp/foo20181116-9699-1o7jc6x/cats20181116-9699-7ofv1c

假设我想在临时目录名“testing”中创建“foo”临时文件,并且一旦请求或会话(irb seision)过期,该“testing”目录应自动删除。如何执行此操作?使用创建临时文件夹。您可以看到问题“”和“”。此答案没有回答问题。他要求在临时文件夹中创建临时文件。也不要给出链接作为答案。如果ruby文档更改了地址怎么办?