0
0
Fork 0

Add coverage for URLValidator (#25591)

This commit is contained in:
Matt Jankowski 2023-07-28 17:12:25 -04:00 committed by GitHub
parent 6602edf064
commit 660993b415
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 70 additions and 23 deletions

View file

@ -1,16 +1,31 @@
# frozen_string_literal: true
class URLValidator < ActiveModel::EachValidator
VALID_SCHEMES = %w(http https).freeze
def validate_each(record, attribute, value)
record.errors.add(attribute, :invalid) unless compliant?(value)
@value = value
record.errors.add(attribute, :invalid) unless compliant_url?
end
private
def compliant?(url)
parsed_url = Addressable::URI.parse(url)
parsed_url && %w(http https).include?(parsed_url.scheme) && parsed_url.host
def compliant_url?
parsed_url.present? && valid_url_scheme? && valid_url_host?
end
def parsed_url
Addressable::URI.parse(@value)
rescue Addressable::URI::InvalidURIError
false
end
def valid_url_scheme?
VALID_SCHEMES.include?(parsed_url.scheme)
end
def valid_url_host?
parsed_url.host.present?
end
end