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