-
-
Save manur/4393962 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use:
class Foo < ActiveRecord::Base
include URLValidator
validate_url :website
end