Class: URLValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/louche/validators/url_validator.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ URLValidator

Returns a new instance of URLValidator.



2
3
4
5
6
# File 'lib/louche/validators/url_validator.rb', line 2

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

Class Method Details

.valid_url?(url, options) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.valid_url?(url, options)
  schemes = [*options.fetch(:schemes)].map(&:to_s)

  if URI::regexp(schemes).match(url)
    begin
      URI.parse(url)
    rescue URI::InvalidURIError
      false
    end
  else
    false
  end
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



8
9
10
11
12
# File 'lib/louche/validators/url_validator.rb', line 8

def validate_each(record, attribute, value)
  unless self.class.valid_url?(value, options)
    record.errors.add(attribute, options.fetch(:message), value: value)
  end
end