简体   繁体   中英

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 if exists? then file.name = "1-"+file.name or something like that

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

Best regards.

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

Another option is to run the command in the shell and deal with the response:

command = "mv *.* #{ new_directory }/"

response = system command

Dealing with existing filenames, etc. is another matter, however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM