Sha256: 4948e19e3712da25b351b1f58e3bf4dc46ec8c0b110d7a1d3564e168fbd7207a

Contents?: true

Size: 1.28 KB

Versions: 4

Compression:

Stored size: 1.28 KB

Contents

require 'uri'
class UrlValidator < ActiveModel::EachValidator

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

  private

  DEFAULT_SCHEMES = [:http, :https].freeze

  def valid_domain?(value, options)
    value_downcased = value.host.to_s.downcase
    options.empty? || options.any? { |d| value_downcased.end_with?(".#{d.downcase}".freeze) }
  end

  def valid_length?(value)
    value.present?
  end

  def valid_scheme?(value, options)
    value_downcased = value.scheme.to_s.downcase
    options.empty? || options.any? { |s| value_downcased == s.to_s.downcase }
  end

  def valid_root?(value)
    ['/', ''].freeze.include?(value.path) && value.query.blank? && value.fragment.blank?
  end

  def valid_uri?(value)
    value.kind_of?(URI::Generic)
  end

  def valid?(value, options)
    valid_length?(value) &&
    valid_uri?(value) &&
    valid_domain?(value, [*(options.fetch(:domain, nil))]) &&
    valid_scheme?(value, [*(options.fetch(:scheme, UrlValidator::DEFAULT_SCHEMES))]) &&
    (options.fetch(:root, false) ? valid_root?(value) : true)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_validation-2.6.0 lib/active_validation/validators/url_validator.rb
active_validation-2.5.0 lib/active_validation/validators/url_validator.rb
active_validation-2.4.0 lib/active_validation/validators/url_validator.rb
active_validation-2.3.0 lib/active_validation/validators/url_validator.rb