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