JBaczuk JBaczuk - 3 months ago 20
Ruby Question

Ruby code not executed after method call

Code is not executed (puts "hey") in the harvest method after the call to searchEmails(page). I'm probably missing something simple with Ruby because I'm just getting back into it.

def searchEmails(page_to_search)
begin
html = @agent.get(url).search('html').to_s
mail = html.scan(/['.'\w|-]*@+[a-z]+[.]+\w{2,}/).map.to_a
base = page_to_search.uri.to_s.split("//", 2).last.split("/", 2).first
mail.each{|e| @file.puts e+";"+base unless e.include? "example.com" or e.include? "email.com" or e.include? "domain.com" or e.include? "company.com" or e.length < 9 or e[0] == "@"}
end
end

def harvest(url)
begin
page = @agent.get(url)
searchEmails(page)
puts "hey"
rescue Exception
end
end

url="www.example.com"
harvest(url)

Answer

@agent.get(url) will fail with a bad url or network outage.

The problem in your code could be written as follows:

def do_something
  begin
    raise
    puts "I will never get here!"
  rescue
  end
end

Since you can't get rid of the raise, you need to do something inside the rescue (most likely log it):

begin
  @agent.get(url)
  # ...
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
       Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,   
       Net::ProtocolError => e
  log(e.message, e.callback)
end