Class: UrlValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/url_validator.rb,
lib/url_validator/engine.rb,
lib/url_validator/version.rb

Defined Under Namespace

Classes: Engine

Constant Summary collapse

VERSION =
'0.0.2'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_optionsObject



15
16
17
# File 'lib/url_validator.rb', line 15

def default_options
  { scheme: nil, allow_no_scheme: false }
end

.valid?(value, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
12
13
# File 'lib/url_validator.rb', line 3

def valid?(value, options = {})
  options = default_options.merge(options)
  uri = URI.parse(value)
  if uri.scheme.nil?
    !!options[:allow_no_scheme]
  else
    options[:scheme] ? options[:scheme].include?(uri.scheme) : true
  end
rescue URI::Error
  false
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



20
21
22
23
24
# File 'lib/url_validator.rb', line 20

def validate_each(record, attribute, value)
  unless self.class.valid?(value, options)
    record.errors.add(attribute, options[:message] || :invalid_url)
  end
end