Sha256: 5e5429c7befe5fa76b04b9c3baf6a0adbc5503833bfee8228b7dff8ecff9bb88

Contents?: true

Size: 1.09 KB

Versions: 2

Compression:

Stored size: 1.09 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('yukonisuru.errors.messages.url'))
  end

  private

  DEFAULT_SCHEMES = [:http, :https]

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

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

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

  def valid?(value, options)
    value.kind_of?(URI::Generic) &&
    valid_domain?(value, [*(options[:domain])]) &&
    valid_scheme?(value, [*(options[:scheme] || UrlValidator::DEFAULT_SCHEMES)]) &&
    (options[:root] ? valid_root?(value) : true)
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yukonisuru-1.0.0 lib/yukonisuru/validators/url_validator.rb
yukonisuru-0.0.1 lib/yukonisuru/validators/url_validator.rb