I have a block of code that looks like this:
def create_page_object(url)
begin
page = Nokogiri::HTML(open(url))
rescue
puts "page not loaded"
end
end
and then I call it via:
result.each do |url|
page = create_page_object(url)
content = make_content(page)
end
Now, in the terminal I see “page not loaded” and then Ruby blows up on me. How can I say, “If page not loaded, stop and go to the next each item”.
Update:
A Scientific Definition of Blowing Up:
test.rb:70:in `get_title': undefined method `xpath' for nil:NilClass (NoMethodError)
from test.rb:40:in `block (2 levels) in process'
from test.rb:35:in `each'
from test.rb:35:in `block in process'
from test.rb:32:in `upto'
from test.rb:32:in `process'
from test.rb:138:in `<main>'
What I believe is happening is because the is not being loaded, it there is no page variable set, which is nil and being throw into the make_content function.
The rescue block is returning the output of
puts(which isnil), you have to make sure you have a document before working with it. Note also that in the rescue you should explicitly returnnilto make clear what is the method returning in that branch. I’d write:I don’t know your especific needs, but it’s usually a bad idea to do “pre-emptive” rescues. Rescue when you have something useful to do, otherwise you’re preventing higher levels to do so.