Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a file, creating directories as necessary in Ruby

Tags:

ruby

Let's say I have a file at /source.txt, and I want to copy it to /a/b/c.txt. /a and /a/b may or may not exist.

Is there a way to copy the file and have it create the necessary parent directories if necessary?

Ideally this would be one command. In particular, I'd like to avoid parsing the file/directory parts of destination path and then manually calling FileUtils.mkdir_p and FileUtils.cp.

Pure Ruby is preferred, though a Rails-dependent solution is acceptable.

like image 751
Craig Walker Avatar asked Feb 16 '11 18:02

Craig Walker


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 ).

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.


1 Answers

Typically it's up to you to make sure that the target directory path exists, so I doubt if any built-in command does what you're looking for.

But using FileUtils.mkdir_p(dir) could be very straightforward, especially by using File.dirname() to parse the path. You could even wrap it in a utility routine, e.g.:

require 'fileutils'  def copy_with_path(src, dst)   FileUtils.mkdir_p(File.dirname(dst))   FileUtils.cp(src, dst) end 
like image 153
maerics Avatar answered Sep 21 '22 16:09

maerics