Class: UriValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/uri_validator.rb

Overview

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, value) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'app/validators/uri_validator.rb', line 6

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? || options[:format].is_a?(Regexp)

  configuration = { message: "is invalid or not responding", format: URI::RFC2396_PARSER.make_regexp(%w[http https]) }
  configuration.update(options)

  if value&.match?(configuration[:format])
    begin
      response = Faraday.head(value)
      object.errors.add(attribute, configuration[:message]) unless response.success?
    rescue StandardError # Recover on DNS failures, SSL errors, etc.
      object.errors.add(attribute, configuration[:message])
    end
  else
    object.errors.add(attribute, configuration[:message])
  end
end