Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

People also ask

How do you create a directory in ruby?

Using Ruby's Mkdir Method To Create A New Directory If you want to create a new folder with Ruby you can use the Dir. mkdir method. If given a relative path, this directory is created under the current path ( Dir. pwd ).

What is __ file __ in Ruby?

In Ruby, the Windows version anyways, I just checked and __FILE__ does not contain the full path to the file. Instead it contains the path to the file relative to where it's being executed from.

How do I change the path of a file in Ruby?

Ruby has a method for this case. It is File::expand_path . Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point.

How do I count the number of files in a directory in ruby?

using ruby how to get number of files in a given Directory,the file count should include count from recursive directories. Eg: folder1(2 files) -----> folder2(4 files) and folder2 is inside folder1. total count for above case should be 6 files.


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)

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?

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.