2017-01-16 00:01:33 +11:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2021-03-19 12:42:43 +11:00
|
|
|
class URLValidator < ActiveModel::EachValidator
|
2023-07-29 07:12:25 +10:00
|
|
|
VALID_SCHEMES = %w(http https).freeze
|
|
|
|
|
2017-01-16 00:01:33 +11:00
|
|
|
def validate_each(record, attribute, value)
|
2023-07-29 07:12:25 +10:00
|
|
|
@value = value
|
|
|
|
|
|
|
|
record.errors.add(attribute, :invalid) unless compliant_url?
|
2017-01-16 00:01:33 +11:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2023-07-29 07:12:25 +10:00
|
|
|
def compliant_url?
|
|
|
|
parsed_url.present? && valid_url_scheme? && valid_url_host?
|
|
|
|
end
|
|
|
|
|
|
|
|
def parsed_url
|
|
|
|
Addressable::URI.parse(@value)
|
2023-01-05 23:33:33 +11:00
|
|
|
rescue Addressable::URI::InvalidURIError
|
|
|
|
false
|
2017-01-16 00:01:33 +11:00
|
|
|
end
|
2023-07-29 07:12:25 +10:00
|
|
|
|
|
|
|
def valid_url_scheme?
|
|
|
|
VALID_SCHEMES.include?(parsed_url.scheme)
|
|
|
|
end
|
|
|
|
|
|
|
|
def valid_url_host?
|
|
|
|
parsed_url.host.present?
|
|
|
|
end
|
2017-01-16 00:01:33 +11:00
|
|
|
end
|