Skip to content

Instantly share code, notes, and snippets.

@manur
Forked from rawsyntax/gist:789162
Last active December 10, 2015 06:18
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 manur/4393962 to your computer and use it in GitHub Desktop.
Save manur/4393962 to your computer and use it in GitHub Desktop.
##
# Validates a URL
#
# If the URI library can parse the value, and the scheme is valid
# then we assume the url is valid
#
require 'addressable/uri'
require 'net/http'
module URLValidator
class ActiveRecord::Base
def validate_url(attribute)
value = self.send(attribute)
begin
uri = Addressable::URI.parse(value)
if !["http","https","ftp"].include?(uri.scheme)
raise Addressable::URI::InvalidURIError
end
rescue Addressable::URI::InvalidURIError
# URI is unparseable, manually try it
begin # check header response
case Net::HTTP.get_response(Addressable::URI.parse(value))
when Net::HTTPSuccess then true
else (self.errors[attribute] << "Not a live URL")
end
rescue # Recover on DNS failures..
self.errors[attribute] << "Invalid URL"
end
end
end
end
end
@manur
Copy link
Author

manur commented Dec 28, 2012

To use:

class Foo < ActiveRecord::Base
include URLValidator
validate_url :website
end

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