Class: OptParseValidator::OptURI

Inherits:
OptBase
  • Object
show all
Defined in:
lib/opt_parse_validator/opts/uri.rb

Overview

Implementation of the URI Option

Direct Known Subclasses

OptProxy, OptURL

Instance Attribute Summary

Attributes inherited from OptBase

#attrs, #option, #required

Instance Method Summary collapse

Methods inherited from OptBase

#advanced?, #alias?, #choices, #default, #help_message_for_default, #help_messages, #initialize, #normalize, #required?, #required_unless, #to_long, #to_s, #to_sym, #value_if_empty

Constructor Details

This class inherits a constructor from OptParseValidator::OptBase

Instance Method Details

#allowed_protocolsArray<String>

Returns:

  • (Array<String>)


15
16
17
# File 'lib/opt_parse_validator/opts/uri.rb', line 15

def allowed_protocols
  @allowed_protocols ||= Array(attrs[:protocols]).map(&:downcase)
end

#append_help_messagesObject

return [ Void ]



7
8
9
10
11
12
# File 'lib/opt_parse_validator/opts/uri.rb', line 7

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

#default_protocolObject

The default protocol (or scheme) to use if none was given



20
21
22
# File 'lib/opt_parse_validator/opts/uri.rb', line 20

def default_protocol
  @default_protocol ||= attrs[:default_protocol]&.downcase
end

#validate(value) ⇒ String

Parameters:

  • value (String)

Returns:

  • (String)


27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/opt_parse_validator/opts/uri.rb', line 27

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