Class: UrlValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UrlValidator

Returns a new instance of UrlValidator.



2
3
4
5
6
7
8
# File 'lib/url_validator.rb', line 2

def initialize(options)
  super

  @domain = options[:domain]
  @permissible_schemes = options[:schemes] || %w(http https)
  @error_message = options[:message] || 'is not a valid url'
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/url_validator.rb', line 10

def validate_each(record, attribute, value)
  if URI::regexp(@permissible_schemes).match(value)
    begin
      uri = URI.parse(value)
      if @domain
        record.errors.add(attribute, 'does not belong to domain', :value => value) unless uri.host == @domain || uri.host.ends_with?(".#{@domain}")
      end
    rescue URI::InvalidURIError
      record.errors.add(attribute, @error_message, :value => value)
    end
  else
    record.errors.add(attribute, @error_message, :value => value)
  end
end