Hi again! Does anybody know if the Ruby API has a way of knowing if a specific page or domain is reachable (without opening it), preferabily in real time? Thanks in advance.
Something like:
require 'net/http'
require 'set'
def working_url?(url, max_redirects=6)
response = nil
seen = Set.new
loop do
url = URI.parse(url)
break if seen.include?(url.to_s)
break if seen.size > max_redirects
seen.add(url.to_s)
response = Net::HTTP.new(url.host, url.port).request_head(url.path)
if response.kind_of?(Net::HTTPRedirection)
url = response['location']
else
break
end
end
response.kind_of?(Net::HTTPSuccess) && url.to_s
end
I suppose it returns true if site is reachable and false if it’s not… Thanks
Or super simple:
require 'open-uri'; begin; open('http://www.www.www') {} rescue '404; error'; end
1 Like