Created
March 14, 2014 07:14
-
-
Save dtaniwaki/9543318 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
require 'net/http' | |
class UriValidator < ActiveModel::EachValidator | |
def validate_each(object, attribute, value) | |
raise(ArgumentError, "A regular expression must be supplied as the :format option of the options hash") unless options[:format].nil? or options[:format].is_a?(Regexp) | |
#configuration = { message: "is invalid or not responding", format: URI::regexp(%w(http https)) } | |
configuration = { check_response: true, format: /(\A\z)|(\A(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?([\/].*)?\z)/ix} | |
configuration.update(options) | |
if value =~ configuration[:format] | |
if configuration[:check_response] | |
begin # check header response | |
case Net::HTTP.get_response(URI.parse(value)) | |
when Net::HTTPSuccess, Net::HTTPRedirection then true | |
else object.errors.add(attribute, configuration[:message] || "is not responding") and false | |
end | |
rescue # Recover on DNS failures.. | |
object.errors.add(attribute, configuration[:message] || "is not responding") and false | |
end | |
end | |
else | |
object.errors.add(attribute, configuration[:message] || :invalid) and false | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment