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
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/url_validator.rb', line 9

def validate(record)
  message = options[:message] || "is not a valid URL"
  schemes = options[:schemes] || %w(http https)
  preffered_schema = options[:preffered_schema] || "#{schemes.first}://"
  options[:attributes].each do |attribute|
    begin
      value = record.send(attribute).to_s
      value.gsub!(/\s+/, "") if value.present?
      next if value.blank? && (options[:allow_blank] || options[:allow_nil])

      uri = Addressable::URI.parse(value)

      if uri.scheme.blank?
        record.send("#{attribute}=", preffered_schema + value)
        value = preffered_schema + value
        uri = Addressable::URI.parse(value)
      end

      unless schemes.include?(uri.scheme)
        raise Addressable::URI::InvalidURIError
      end

      normalized_value = record.send("#{attribute}_normalized")

      if value.blank? && (!options[:allow_blank] || !options[:allow_nil])
        raise Addressable::URI::InvalidURIError
      end
    rescue Addressable::URI::InvalidURIError
      record.errors.add(attribute, message, :value => uri.to_s)
    end
  end

end