How do I create directory if none exists using File class in Ruby?
ruby
Solution
You can use FileUtils to recursively create parent directories, if they are not already present:
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
Problem
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 `somedir` or `some_subdir` or both in the path, I want it to automagically create it. How can I do that?