[英]How do I access one of my models from within a ruby script in the /lib/ folder in my Rails 3 app?
[英]Ruby on Rails: How do I move all files from one folder to another folder?
但是我還需要一種方法來重命名它們以防發生沖突。
比如if exists? then file.name = "1-"+file.name
if exists? then file.name = "1-"+file.name
或類似的東西
也許這樣的事情對你有用:
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
此致。
上面的代碼有效,但有點錯誤,您正在使用if File.exists?(file)
,它正在檢查文件是否存在於原始文件夾/或子文件夾中,(這是沒有用的,因為它已被讀取,因為它已經存在)。 您需要檢查文件是否已存在於目標文件夾中。 由於這種語法,“else”永遠不會被執行。 並且所有文件都被命名為“1-filename”。 正確的是使用
if File.exists? File.join(destination, File.basename(file))
另一種選擇是在 shell 中運行命令並處理響應:
command = "mv *.* #{ new_directory }/"
response = system command
然而,處理現有文件名等是另一回事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.