Welcome to mirror list, hosted at ThFree Co, Russian Federation.

addressable_url_validator.rb « validators « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ee6a5a118506b6eb45948312018f761af72eee0e (plain)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# AddressableUrlValidator
#
# Custom validator for URLs. This is a
#
# By default, only URLs for http, https, ssh, and git protocols will be considered valid.
# Provide a `:protocols` option to configure accepted protocols.
#
# Example:
#
#   class User < ActiveRecord::Base
#     validates :personal_url, addressable_url: true
#
#     validates :ftp_url, addressable_url: { protocols: %w(ftp) }
#
#     validates :git_url, addressable_url: { protocols: %w(http https ssh git) }
#   end
#
class AddressableUrlValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless valid_url?(value)
      record.errors.add(attribute, "must be a valid URL")
    end
  end

  private

  def valid_url?(value)
    return false unless value

    value.strip!

    valid_uri?(value) && valid_protocol?(value)
  rescue Addressable::URI::InvalidURIError
    false
  end

  def default_options
    @default_options ||= { protocols: %w(http https ssh git) }
  end

  def valid_uri?(value)
    Addressable::URI.parse(value).is_a?(Addressable::URI)
  end

  def valid_protocol?(value)
    options = default_options.merge(self.options)
    !!(value =~ /\A#{URI.regexp(options[:protocols])}\z/)
  end
end