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> 这导致我的“执行此功能返回真实”的条件以评估为false。为什么此函数击中第一个返回语句(就像我使用过的其他所有语言一样)时不会退出

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

有帮助吗?

解决方案

显然, Net::HTTP.get_response 已通过 Net::HTTPFound 实例为 http 参数进入内部块。所以, return 陈述从未达到过,你的 download_torrent 方法返回了最后一个对象“堆栈”,恰好是 Net::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)). 。没有代码块,它更简单,简单地将内容返回为字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top