Sha256: 0bded2a8eb03f2c3c292c0ab9bd5063a84b16b73a3e6c7ea8156b2d15b6c713b

Contents?: true

Size: 1.2 KB

Versions: 6

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

module OptParseValidator
  # Implementation of the URI Option
  class OptURI < OptBase
    # return [ Void ]
    def append_help_messages
      option << "Allowed Protocols: #{allowed_protocols.join(', ')}" unless allowed_protocols.empty?
      option << "Default Protocol if none provided: #{default_protocol}" if default_protocol

      super
    end

    # @return [ Array<String> ]
    def allowed_protocols
      @allowed_protocols ||= Array(attrs[:protocols]).map(&:downcase)
    end

    # The default protocol (or scheme) to use if none was given
    def default_protocol
      @default_protocol ||= attrs[:default_protocol]&.downcase
    end

    # @param [ String ] value
    #
    # @return [ String ]
    def validate(value)
      uri = Addressable::URI.parse(value)

      uri = Addressable::URI.parse("#{default_protocol}://#{value}") if !uri.scheme && default_protocol

      unless allowed_protocols.empty? || allowed_protocols.include?(uri.scheme&.downcase)
        # For future refs: will have to check if the uri.scheme exists,
        # otherwise it means that the value was empty
        raise Addressable::URI::InvalidURIError
      end

      uri.to_s
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
opt_parse_validator-1.10.1 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.10.0 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.9.5 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.9.4 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.9.3 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.9.2 lib/opt_parse_validator/opts/uri.rb