我刚开始学习ruby,我正在尝试编辑以下脚本。代码是在创建目录时下载文件。
def download_files
puts "Downloading #{@base_url} to #{backup_path} from site..."
puts
file_list_by_time = get_file_list_by_time
if file_list_by_time.count == 0
puts "No files to download. Possible reasons:\n\t* Accept regex didn't let any files through (Accept Regex: \"#{@accept_regex.to_s}\")\n\t* Site is not in site."
return
end
count = 0
file_list_by_time.each do |file_remote_info|
count += 1
file_url = file_remote_info[:file_url]
file_id = file_remote_info[:file_id]
file_time = file_remote_info[:time]
file_path_elements = file_id.split('/')
if file_id == ""
dir_path = backup_path
file_path = backup_path + 'index.html'
elsif file_url[-1] == '/' or not file_path_elements[-1].include? '.'
dir_path = backup_path + file_path_elements[0..-1].join('/')
file_path = backup_path + file_path_elements[0..-1].join('/') + '/index.html'
else
dir_path = backup_path + file_path_elements[0..-2].join('/')
file_path = backup_path + file_path_elements[0..-1].join('/')
end
unless File.exists? file_path
open('myfile.txt', 'a') do |f|
f.puts ("http://example.com/#{file_time}id_/#{file_url}")
end
begin
structure_dir_path dir_path
open(file_path, "wb") do |file|
begin
rescue OpenURI::HTTPError => e
puts "#{file_url} # #{e}"
file.write(e.io.read)
rescue StandardError => e
puts "#{file_url} # #{e}"
end
end
rescue StandardError => e
puts "#{file_url} # #{e}"
end
puts "#{file_url} -> #{file_path} (#{count}/#{file_list_by_time.size})"
else
puts "#{file_url} # #{file_path} already exists. (#{count}/#{file_list_by_time.size})"
end
end
puts
puts "Download complete, saved in #{backup_path} (#{file_list_by_time.size} files)"
end
end
我想将其更改为仅将完整文件URL保存为文本文件,即保存URL而不下载文件。
我将以下内容添加到完美运行的代码中。我现在只需要停止脚本下载文件。
open('myfile.txt', 'a') do |f|
f.puts ("http://example.com/#{file_time}id_/#{file_url}")
end
我尝试将部分从structure_dir_path dir_path
删除到最后,但我一直收到错误消息。任何想法如何才能正确实现?
答案 0 :(得分:0)
要停止处理,只需从方法内的任何位置返回,包括从块内返回。例如:
open('myfile.txt', 'a') do |f|
url = "http://example.com/#{file_time}id_/#{file_url}"
f.puts url
return url
end