Sha256: ce9d88850678e32c8120642dd776c97aa918f9e7ffbae2e2786fa34ea56172a8

Contents?: true

Size: 1.13 KB

Versions: 3

Compression:

Stored size: 1.13 KB

Contents

require 'uri'
class UrlValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    uri = URI.parse(value)
    raise URI::InvalidURIError unless valid?(uri, options)
  rescue URI::InvalidURIError
    record.errors[attribute] << (options[:message] || I18n.t('errors.messages.url'))
  end

  private

  DEFAULT_SCHEMES = [:http, :https]

  def self.validate_domain(uri, domains)
    host_downcased = uri.host.to_s.downcase
    domains.empty? || domains.any? { |domain| host_downcased.end_with?(".#{domain.downcase}") }
  end

  def self.validate_scheme(uri, schemes)
    scheme_downcased = uri.scheme.to_s.downcase
    schemes.empty? || schemes.any? { |scheme| scheme_downcased == scheme.to_s.downcase }
  end

  def self.validate_root(uri)
    ['/', ''].include?(uri.path) && uri.query.blank? && uri.fragment.blank?
  end

  def valid?(uri, options)
    uri.kind_of?(URI::Generic) \
      && self.class.validate_domain(uri, [*(options[:domain])]) \
      && self.class.validate_scheme(uri, [*(options[:scheme] || UrlValidator::DEFAULT_SCHEMES)]) \
      && (!!options[:root] ? self.class.validate_root(uri) : true)
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
flash_validators-1.1.0 lib/flash_validators/validators/url_validator.rb
flash_validators-1.0.0 lib/flash_validators/validators/url_validator.rb
flash_validators-0.0.1 lib/flash_validators/validators/url_validator.rb