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.



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

def initialize(options)
  options.reverse_merge!(:schemes => %w(http https))
  options.reverse_merge!(:message => :url)
  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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

def validate_each(record, attribute, value)
  schemes = [*options.fetch(:schemes)].map(&:to_s)
  begin
    uri = URI.parse(value)
    unless uri && schemes.include?(uri.scheme)
      record.errors.add(attribute, options.fetch(:message), :value => value)
    end
  rescue URI::InvalidURIError
    record.errors.add(attribute, options.fetch(:message), :value => value)
  end
end