~cytrogen/masto-fe

ref: 8eb09c6f72dbb9a4353ff2027a9fc40ad3292e51 masto-fe/app/validators/url_validator.rb -rw-r--r-- 611 bytes
8eb09c6f — Michael Stanclift [Glitch] Keep version string displayed without breakpoints in UI 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# frozen_string_literal: true

class URLValidator < ActiveModel::EachValidator
  VALID_SCHEMES = %w(http https).freeze

  def validate_each(record, attribute, value)
    @value = value

    record.errors.add(attribute, :invalid) unless compliant_url?
  end

  private

  def compliant_url?
    parsed_url.present? && valid_url_scheme? && valid_url_host?
  end

  def parsed_url
    Addressable::URI.parse(@value)
  rescue Addressable::URI::InvalidURIError
    false
  end

  def valid_url_scheme?
    VALID_SCHEMES.include?(parsed_url.scheme)
  end

  def valid_url_host?
    parsed_url.host.present?
  end
end