Class: ActiveModel::Validations::UrlValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UrlValidator

Returns a new instance of UrlValidator.



8
9
10
11
12
# File 'lib/validate_url.rb', line 8

def initialize(options)
  options.reverse_merge!(:schemes => %w(http https))
  options.reverse_merge!(:message => "is not a valid URL")
  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/validate_url.rb', line 14

def validate_each(record, attribute, value)
  schemes = [*options.fetch(:schemes)].map(&:to_s)

  if URI::regexp(schemes).match(value)
    begin
      URI.parse(value)
    rescue URI::InvalidURIError
      record.errors.add(attribute, options.fetch(:message), :value => value)
    end
  else
    record.errors.add(attribute, options.fetch(:message), :value => value)
  end
end