Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

Copy a file, creating directories as necessary in 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.

question from:https://stackoverflow.com/questions/5020710/copy-a-file-creating-directories-as-necessary-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...