الحصول على قيمة إرجاع من كتل متعددة مع روبي

StackOverflow https://stackoverflow.com/questions/3588880

  •  01-10-2019
  •  | 
  •  

سؤال


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> مما يسبب "هل تعود هذه الوظيفة هذه الحقيقية" لتقييم كاذبة. لماذا لا تخرج هذه الوظيفة عندما تصل إلى بيان الإرجاع الأول (مثل كل لغة أخرى استخدمتها)

أعلم أن هذا سؤال مبتدئ من روبي (أنا قافية!) ، لكنني أقدر المساعدة.

هل كانت مفيدة؟

المحلول

فيما يبدو، 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