N N
N N

Reputation: 1638

Copy folder and its content in ruby

My project structure looks like this:

Project_root
 |__Templates
 |  |__Report_Template
 |
 |__Product
    |__product.rb

What code should I write in product.rb in order to copy Report_Template folder and its content into Product folder? I tried to use FileUtils.cp_r, but then I will have to give full path of source folder and if in a future I move Project_root, there will be issues.

Upvotes: 0

Views: 49

Answers (1)

Amadan
Amadan

Reputation: 198314

As Kenney says, you can get the path from which the program started, in __dir__. Here I use Pathname class for easier path manipulation, but it is entirely optional (you can use File#join etc. just as well):

require 'pathname'
templates_pathname = Pathname.new(__dir__) + "../Templates/Report_Template"
# optional:
templates_path = templates_pathname.realpath.to_s

Pathname#realpath will give you the absolute path, if you need it; but FileUtils#cp_r will happily accept a Pathname (i.e. templates_pathname above), and won't mind it's not absolute.

Upvotes: 1

Related Questions