Skip to content

Instantly share code, notes, and snippets.

@skozz
Forked from murdoch/check-uri.rb
Created September 26, 2017 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skozz/1ba83197a2564efae985e17bd02c9399 to your computer and use it in GitHub Desktop.
Save skozz/1ba83197a2564efae985e17bd02c9399 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment