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

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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.

Solution 3 - Ruby

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

Solution 4 - Ruby

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)

Solution 5 - Ruby

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!

Solution 6 - Ruby

Along similar lines (and depending on your structure), this is how we solved where to store screenshots:

In our env setup (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

  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?

Solution 7 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcamillionView Question on Stackoverflow
Solution 1 - RubyEurekaView Answer on Stackoverflow
Solution 2 - RubyAndrey Mikhaylov - lolmausView Answer on Stackoverflow
Solution 3 - RubyLicyscaView Answer on Stackoverflow
Solution 4 - RubyironsandView Answer on Stackoverflow
Solution 5 - RubyskplunkerinView Answer on Stackoverflow
Solution 6 - RubyShell BrysonView Answer on Stackoverflow
Solution 7 - RubyCopyLeftView Answer on Stackoverflow