2016-01-11 36 views
0

我剛開始學習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

返回從早期方法

停止處理,從任何地方只是返回你的方法裏面,包括從區塊內。例如:

open('myfile.txt', 'a') do |f| 
    url = "http://example.com/#{file_time}id_/#{file_url}" 
    f.puts url 
    return url 
end 
+0

這沒有奏效,它只是保存了第一個url並停止了執行 – user2334436