Sha256: 691b8c492b5c85c8d14d469dacb2be77085188587a0a1efcf8ae6f664e0edb8c

Contents?: true

Size: 1.19 KB

Versions: 9

Compression:

Stored size: 1.19 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 ||= [*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

9 entries across 9 versions & 1 rubygems

Version Path
opt_parse_validator-1.9.1 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.9.0 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.8.2 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.8.1 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.8.0 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.7.4 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.7.3 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-1.7.2 lib/opt_parse_validator/opts/uri.rb
opt_parse_validator-0.0.17.1 lib/opt_parse_validator/opts/uri.rb