Sha256: 45ec97a38a02a2b4cc037ae6613d17156b9aae98c122b056487f870dac1972b5

Contents?: true

Size: 782 Bytes

Versions: 4

Compression:

Stored size: 782 Bytes

Contents

class UrlValidator < ActiveModel::EachValidator
  def initialize(options)
    super

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

  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
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
blog_basic-0.1.14 lib/url_validator.rb
blog_basic-0.1.13 lib/url_validator.rb
blog_basic-0.1.9 lib/url_validator.rb
blog_basic-0.1.6 lib/url_validator.rb