Skip to content

Instantly share code, notes, and snippets.

@murdoch
Created August 24, 2011 16:51
Show Gist options
  • Save murdoch/1168520 to your computer and use it in GitHub Desktop.
Save murdoch/1168520 to your computer and use it in GitHub Desktop.
Check if uri exists
## just some ways to check if a url exists
# method 1 - from Simone Carletti
require "net/http"
url = URI.parse("http://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)
# method 2 - from some kid on the internet
require 'open-uri'
require 'net/http'
def remote_file_exists?(url)
url = URI.parse(url)
Net::HTTP.start(url.host, url.port) do |http|
return http.head(url.request_uri).code == "200"
end
end
# method 3 - from another kid on the internet in response method 2
require 'rubygems'
require 'rest-open-uri'
def remote_file_exist?(url)
open( url , :method => :head).status rescue false
end
# method 4 - from http://rawsyntax.com/post/4544397323/url-validation-in-rails-3-and-ruby-in-general
require 'addressable/uri'
class Example
include ActiveModel::Validations
##
# Validates a URL
#
# If the URI library can parse the value, and the scheme is valid
# then we assume the url is valid
#
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
begin
uri = Addressable::URI.parse(value)
if !["http","https","ftp"].include?(uri.scheme)
raise Addressable::URI::InvalidURIError
end
rescue Addressable::URI::InvalidURIError
record.errors[attribute] << "Invalid URL"
end
end
end
validates :field, :url => true
end
@loicginoux
Copy link

thx! for method 1 - add support for "https" with:

url = URI.parse("http://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
req.use_ssl = true if url.scheme == 'https'
res = req.request_head(url.path)

@StepanPakholok
Copy link

validate :url_should_be_accessible
...

def url_should_be_accessible
    require 'net/http'
    success = true
    begin
      success = false unless Net::HTTP.get_response(URI.parse(self.url)).is_a?(Net::HTTPSuccess)
    rescue
      success = false
    end
    errors.add(:url, 'cannot be accessed in Internet') unless success
  end

@BasileKoko
Copy link

I found Faraday gem to be very helpful as well.
require 'faraday'

def url_exists?(url)
res = Faraday.get(url).status
end

#res => 200 when url exists
#res => 404 when url does not exit

@dsandstrom
Copy link

def remote_file_exists?(url)
  uri = URI.parse(url)
  Net::HTTP.get_response(uri).code == '200'
end

@luelher
Copy link

luelher commented Jun 18, 2018

This work for me:

def working_url?(url_str)
    begin
      Net::HTTP.get_response(URI.parse(url_str)).is_a?(Net::HTTPSuccess)
    rescue
      false
    end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment