0

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

我的函数不会返回布尔意义上的“真”。它不断返回<Net::HTTPFound:0x3186c60>,这导致我的“此函数是否返回 true”有条件地评估为 false。为什么这个函数在遇到第一个返回语句时没有退出(就像我使用过的所有其他语言一样)

我知道这完全是一个 Ruby 新手(我押韵!)的问题,但我感谢您的帮助。

4

1 回答 1

1

显然,已将实例作为参数Net::HTTP.get_response传递到内部块中。因此,从未到达过语句,并且您的方法返回了“堆栈上”的最后一个对象,该对象恰好是.Net::HTTPFoundhttpreturndownload_torrentNet::HTTP.get_response

如果该描述有点模糊,这里有一个较短的示例。使用return true部分,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)). 没有代码块更简单,只需将内容作为字符串返回。

于 2010-08-28T00:29:07.847 回答