Frage


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

Meine Funktion nicht zurück ‚true‘ im boolean Sinne. Es hält <Net::HTTPFound:0x3186c60> Rückkehr, die bewirkt, dass mein ‚tut diese Funktion return true‘ bedingte false zu bewerten. Warum verläßt diese Funktion nicht, wenn es die erste return-Anweisung trifft (wie jede andere Sprache, die ich verwendet habe)

Ich weiß, das ist total ein Ruby-Neuling (I gereimten!) Frage, aber ich schätze die Hilfe.

War es hilfreich?

Lösung

Offenbar Net::HTTP.get_response vergangen Net::HTTPFound Instanz als http Parameter in Innenblock. Daher wurde return Aussage nie erreicht und Ihre download_torrent-Methode zurück das letzte Objekt „auf dem Stapel“, der Rückgabewert von Net::HTTP.get_response passiert sein.

Wenn diese Beschreibung etwas vage ist, ist hier ein kürzeres Beispiel. Mit return true Teil wird do_it Methode true zurückzukehren. Ohne sie wird do_it Methode Objekt von do_that zurück zurück.

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

ich wenig Erfahrung mit net/http Paket haben, werden Sie wahrscheinlich irgendwie docs und handle Net::HTTPFound Antwort in Ihrem case Operator lesen müssen.

Persönlich dies immer für mich gearbeitet Webseite Inhalte in Holen: Net::HTTP.get(URI.parse(url)). Es ist einfacher, ohne Code-Block und gibt einfach Inhalt als String zurück.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top