Class: ActiveModel::Validations::UrlValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/validate_url.rb

Constant Summary collapse

RESERVED_OPTIONS =
[:schemes, :no_local]

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UrlValidator

Returns a new instance of UrlValidator.



11
12
13
14
15
16
17
18
# File 'lib/validate_url.rb', line 11

def initialize(options)
  options.reverse_merge!(schemes: %w(http https))
  options.reverse_merge!(message: :url)
  options.reverse_merge!(no_local: false)
  options.reverse_merge!(public_suffix: false)

  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/validate_url.rb', line 20

def validate_each(record, attribute, value)
  schemes = [*options.fetch(:schemes)].map(&:to_s)
  begin
    uri = URI.parse(value)
    host = uri && uri.host
    scheme = uri && uri.scheme

    valid_raw_url = scheme && value =~ /\A#{URI::regexp([scheme])}\z/
    valid_scheme = host && scheme && schemes.include?(scheme)
    valid_no_local = !options.fetch(:no_local) || (host && host.include?('.'))
    valid_suffix = !options.fetch(:public_suffix) || (host && PublicSuffix.valid?(host, :default_rule => nil))

    unless valid_raw_url && valid_scheme && valid_no_local && valid_suffix
      record.errors.add(attribute, options.fetch(:message), value: value)
    end
  rescue URI::InvalidURIError
    record.errors.add(attribute, :url, filtered_options(value))
  end
end