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