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