开发者

Checking URL availability Ruby on Rails

开发者 https://www.devze.com 2023-03-30 04:12 出处:网络
Suppose that after primitive validation of user submitted URL I have the string that looks like URL: url = \'http://www.thisdomaindoesntexist.com/dont_even_ask_about/this/uri\'

Suppose that after primitive validation of user submitted URL I have the string that looks like URL:

url = 'http://www.thisdomaindoesntexist.com/dont_even_ask_about/this/uri'

How can I check if its available or not?

I tried this in my is_valid_link function:

require "net/http"
url = URI.parse(url)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)

It works if the server exists giving me back the HTTP response, but the problem is that in case of bad url I get an error like this:

SocketError in PostsController#create

getaddrinfo: nodename nor servname provided, or not known

How should I do this kind of validation properly?

Thanks 开发者_StackOverflow中文版in advance.


You can use rescue to catch errors and do some error handling

begin
  require "net/http"
  url = URI.parse(url)
  req = Net::HTTP.new(url.host, url.port)
  res = req.request_head(url.path)
rescue
  # error occured, return false
  false
else
  # valid site
  true
end

Use rescue inline:

require "net/http"
url = URI.parse(url)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path) rescue false


I've looked for a way to check if URL existed for 5 hours and this thread actually helped me. I'm a newbie in rails and wanted to find something easy.

Here how I integrated the code into controller:

require "net/http"
def url
url = URI.parse('http://www.url that you want to check.com/' + "/")
end
def req
@req = Net::HTTP.new(url.host, url.port)
end
def res #res
@res = req.request_head(url.path) 
rescue
    false
end

def test
    if res == false
    "something"
    else
    "another thing"
end

you have to make sure that URL ends with "/", else the code won't work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号