Получение возвращаемого значения из нескольких блоков с Ruby - PullRequest
0 голосов
/ 28 августа 2010

require 'net/http';
require 'uri';
require 'rexml/document';
require 'sqlite3';

def download_torrent(episode_id, torrent_url, limit = 10)
  # Check to make sure we haven't been trapped in an infinite loop
  if limit == 0 then
    puts "Too much redirection, skipping #{episode_id}";
    return true;
  else
    # Convert the URL of the torrent into a URI usable by Net:HTTP
    torrent_uri = URI.parse(torrent_url);
    # Open a connection to the torrent URL
    Net::HTTP.get_response(torrent_uri) { |http|
      # Check to see if we were able to connect to the torrent URL
      case http
      # We connected just fine
      when Net::HTTPSuccess then
        # Create a torrent file to store the data in
        File.open("#{episode_id}.torrent", 'wb') { |torrent_file|
          # Write the torrent data to the torrent file
          torrent_file.write(http.body);
          # Close the torrent file
          torrent_file.close
          # Check to see if we've download a 'locked' torrent file (html) instead of a regular torrent (.torrent)
          if(File.exists?('download.torrent.html'))
            # Delete the html file
            File.delete('download_torrent.html');
            return false;
          else
            return true;
          end
        }
      when Net::HTTPRedirection then
          download_torrent(episode_id, http['location'], limit - 1);
      end
    }
  end
end

Моя функция не возвращает 'true' в логическом смысле. Он продолжает возвращать <Net::HTTPFound:0x3186c60>, что заставляет мое условие 'эта функция возвращает true' условно вычислять как false. Почему эта функция не завершается, когда выполняет первое выражение возврата (как и любой другой язык, который я использовал)

Я знаю, что это вопрос Руби Ньюби (я рифмовался!), Но я ценю помощь.

1 Ответ

1 голос
/ 28 августа 2010

Очевидно, Net::HTTP.get_response передал экземпляр Net::HTTPFound как параметр http во внутренний блок.Следовательно, оператор return никогда не был достигнут, и ваш метод download_torrent возвратил последний объект "в стеке", что является возвращаемым значением Net::HTTP.get_response.

Если это описание немного расплывчато, вотболее короткий пример.С return true part, метод do_it вернет true.Без него метод do_it вернет объект, возвращенный do_that.

def do_it
  do_that {|param|
#    return true;
  }
end

У меня мало опыта с пакетом net/http, вам, вероятно, придется читать документы и обрабатывать ответ Net::HTTPFound вВаш оператор case каким-то образом.

Лично для меня это всегда работало при получении содержимого веб-страницы: Net::HTTP.get(URI.parse(url)).Проще без блока кода и просто возвращает содержимое в виде строки.

...