Conseguir un valor de retorno de bloques múltiples con Ruby
Pregunta
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
Mi función no devuelve 'verdadero' en el sentido de Boole. Se sigue volviendo <Net::HTTPFound:0x3186c60>
que hace que mi 'hace esto retorno de la función verdadera' condicional para evaluar a falso. ¿Por qué esta función no saliendo cuando llega a la primera instrucción de retorno (como cualquier otro lenguaje que he usado)
Sé que esto es totalmente un rubí Novato (I rimado!) Pregunta, pero aprecio la ayuda.
Solución
ejemplo Net::HTTP.get_response
Aparentemente, Net::HTTPFound
ha pasado como parámetro http
en el bloque interno. Por lo tanto, no se alcanzó comunicado return
y su método de download_torrent
regresó el último objeto "en la pila", que pasa a ser el valor de retorno de Net::HTTP.get_response
.
Si esa descripción es un poco vago, aquí hay un ejemplo más corto. Con return true
parte, el método do_it
volverá true
. Sin él, el método do_it
volverá objeto devuelto por do_that
.
def do_it
do_that {|param|
# return true;
}
end
Tengo poca experiencia con el paquete net/http
, es probable que tenga que leer documentos y la respuesta Net::HTTPFound
mango en su operador case
de alguna manera.
En lo personal, esto siempre ha trabajado para mí en ir a buscar contenidos de páginas web: Net::HTTP.get(URI.parse(url))
. Es más sencillo sin bloque de código y simplemente devuelve el contenido como cadena.