How do I create directory if none exists using File class in Ruby?

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?


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

For those looking for a way to create a directory if it doesn't exist, here's the simple solution:

require 'fileutils'

FileUtils.mkdir_p 'dir_name'

Based on Eureka's comment.


directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

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!


How about using Pathname?

require 'pathname'
some_path = Pathname("somedir/some_subdir/some-file.html")
some_path.dirname.mkdir_p
some_path.write(builder.to_html)