Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How do I move all files from one folder to another folder?

But I also need a way to rename them incase there are conflicts.

Like if exists? then file.name = "1-"+file.name or something like that

like image 421
NullVoxPopuli Avatar asked Jul 20 '10 16:07

NullVoxPopuli


2 Answers

Maybe something like this works for you:

origin = '/test_dir'
destination = '/another_test_dir'

Dir.glob(File.join(origin, '*')).each do |file|
  if File.exists? File.join(destination, File.basename(file))
    FileUtils.move file, File.join(destination, "1-#{File.basename(file)}")
  else
    FileUtils.move file, File.join(destination, File.basename(file))
  end
end
like image 177
DBA Avatar answered Sep 26 '22 10:09

DBA


Above code works, but little mistake, You are using if File.exists?(file), which is checking if file exits in origin folder/or subfolder,( which is of no use, since it was read because it already exists). You need to check if file already exists in destination folder. Because of this syntax the "else" is never getting executed. And all files are getting named like "1-filename". Correct would be to use

if File.exists? File.join(destination, File.basename(file))
like image 38
xcr Avatar answered Sep 23 '22 10:09

xcr