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
19
# 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)
  options.reverse_merge!(accept_array: false)

  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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

def validate_each(record, attribute, value)
  schemes = [*options.fetch(:schemes)].map(&:to_s)
  if value.respond_to?(:each)
    # Error out if we're not allowing arrays
    if !options.include?(:accept_array) || !options.fetch(:accept_array)
      record.errors.add(attribute, :url, **filtered_options(value))
    end

    # We have to manually handle `:allow_nil` and `:allow_blank` since it's not caught by
    # ActiveRecord's own validators. We do that by just removing all the nil's if we want to
    # allow them so it's not passed on later.
    value = value.reject(&:nil?) if options.include?(:allow_nil) && options.fetch(:allow_nil)
    value = value.reject(&:blank?) if options.include?(:allow_blank) && options.fetch(:allow_blank)

    result = value.flat_map { |v| validate_url(record, attribute, v, schemes) }
    errors = result.reject(&:nil?)

    return errors.any? ? errors.first : true
  end

  validate_url(record, attribute, value, schemes)
end