如果在 Ruby 中使用 File 类不存在目录,如何创建目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12617152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create directory if none exists using File class in Ruby?
提问by marcamillion
I have this statement:
我有这样的声明:
File.open(some_path, 'w+') { |f| f.write(builder.to_html) }
Where
在哪里
some_path = "somedir/some_subdir/some-file.html"
What I want to happen is, if there is no directory called somediror some_subdiror both in the path, I want it to automagically create it.
我希望发生的是,如果有一个名为没有目录somedir或some_subdir路径或两个,我希望它自动地创建它。
How can I do that?
我怎样才能做到这一点?
回答by Eureka
You can use FileUtils to recursively create parent directories, if they are not already present:
您可以使用 FileUtils 递归创建父目录(如果它们尚不存在):
require 'fileutils'
dirname = File.dirname(some_path)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end
Edit: Here is a solution using the core libraries only (reimplementing the wheel, not recommended)
编辑:这是一个仅使用核心库的解决方案(重新实现轮子,不推荐)
dirname = File.dirname(some_path)
tokens = dirname.split(/[\/\]/) # don't forget the backslash for Windows! And to escape both "\" and "/"
1.upto(tokens.size) do |n|
dir = tokens[0...n]
Dir.mkdir(dir) unless Dir.exist?(dir)
end
回答by Andrey Mikhaylov - lolmaus
回答by Licysca
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
回答by skplunkerin
Based on others answers, nothing happened (didn't work). There was no error, and no directory created.
根据其他人的答案,什么也没发生(不起作用)。没有错误,也没有创建目录。
Here's what I needed to do:
这是我需要做的:
require 'fileutils'
response = FileUtils.mkdir_p('dir_name')
I needed to create a variable to catch the response that FileUtils.mkdir_p('dir_name')sends back... then everything worked like a charm!
我需要创建一个变量来捕捉FileUtils.mkdir_p('dir_name')发回的响应......然后一切都像魅力一样!
回答by CopyLeft
The top answer's "core library" only solution was incomplete. If you want to only use core libraries, use the following:
最佳答案的“核心库”唯一解决方案不完整。如果您只想使用核心库,请使用以下命令:
target_dir = ""
Dir.glob("/#{File.join("**", "path/to/parent_of_some_dir")}") do |folder|
target_dir = "#{File.expand_path(folder)}/somedir/some_subdir/"
end
# Splits name into pieces
tokens = target_dir.split(/\//)
# Start at '/'
new_dir = '/'
# Iterate over array of directory names
1.upto(tokens.size - 1) do |n|
# Builds directory path one folder at a time from top to bottom
unless n == (tokens.size - 1)
new_dir << "#{tokens[n].to_s}/" # All folders except innermost folder
else
new_dir << "#{tokens[n].to_s}" # Innermost folder
end
# Creates directory as long as it doesn't already exist
Dir.mkdir(new_dir) unless Dir.exist?(new_dir)
end
I needed this solution because FileUtils' dependency gem rmagick prevented my Rails app from deploying on Amazon Web Services since rmagick depends on the package libmagickwand-dev (Ubuntu) / imagemagick (OSX) to work properly.
我需要这个解决方案是因为 FileUtils 的依赖 gem rmagick 阻止了我的 Rails 应用程序在 Amazon Web Services 上部署,因为 rmagick 依赖包 libmagickwand-dev (Ubuntu) / imagemagick (OSX) 才能正常工作。
回答by ironsand
How about using Pathname?
怎么用Pathname?
require 'pathname'
some_path = Pathname("somedir/some_subdir/some-file.html")
some_path.dirname.mkdir_p
some_path.write(builder.to_html)
回答by Shell Bryson
Along similar lines (and depending on your structure), this is how we solved where to store screenshots:
沿着类似的路线(并且取决于您的结构),这就是我们解决存储屏幕截图的位置的方法:
In our env setup (env.rb)
在我们的环境设置 (env.rb)
screenshotfolder = "./screenshots/#{Time.new.strftime("%Y%m%d%H%M%S")}"
unless File.directory?(screenshotfolder)
FileUtils.mkdir_p(screenshotfolder)
end
Before do
@screenshotfolder = screenshotfolder
...
end
And in our hooks.rb
在我们的 hooks.rb
screenshotName = "#{@screenshotfolder}/failed-#{scenario_object.title.gsub(/\s+/,"_")}-#{Time.new.strftime("%Y%m%d%H%M%S")}_screenshot.png";
@browser.take_screenshot(screenshotName) if scenario.failed?
embed(screenshotName, "image/png", "SCREENSHOT") if scenario.failed?

![ruby Array.empty 的相反方法是什么?或 [].empty?红宝石](/res/img/loading.gif)