1
0

url_validator.rb 611 B

12345678910111213141516171819202122232425262728293031
  1. # frozen_string_literal: true
  2. class URLValidator < ActiveModel::EachValidator
  3. VALID_SCHEMES = %w(http https).freeze
  4. def validate_each(record, attribute, value)
  5. @value = value
  6. record.errors.add(attribute, :invalid) unless compliant_url?
  7. end
  8. private
  9. def compliant_url?
  10. parsed_url.present? && valid_url_scheme? && valid_url_host?
  11. end
  12. def parsed_url
  13. Addressable::URI.parse(@value)
  14. rescue Addressable::URI::InvalidURIError
  15. false
  16. end
  17. def valid_url_scheme?
  18. VALID_SCHEMES.include?(parsed_url.scheme)
  19. end
  20. def valid_url_host?
  21. parsed_url.host.present?
  22. end
  23. end