Class: ActiveModel::Validations::UrlValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/url_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/url_validator.rb', line 9

def validate(record)
  message = options[:message] || "is not a valid URL"
  schemes = options[:schemes] || %w(http https)
  url_regexp = /^((#{schemes.join('|')}):\/\/){0,1}[a-z0-9]+([a-z0-9\-\.]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
  preffered_schema = options[:preffered_schema] || "#{schemes.first}://"

  options[:attributes].each do |attribute|
    value = record.send(attribute).to_s
    next if value.blank? && (options[:allow_blank] || options[:allow_nil])
    record.send("#{attribute}=", preffered_schema << value) if !value.start_with?(*schemes)
    normalized_value = record.send("#{attribute}_normalized")
    begin
      uri = Addressable::URI.parse(value)
      unless url_regexp =~ normalized_value
        record.errors.add(attribute, message, :value => uri.to_s)
      end
    rescue Addressable::URI::InvalidURIError
      record.errors.add(attribute, message, :value => uri.to_s)
    end
  end

end