Class: TTY::Option::Parser::Keywords

Inherits:
Object
  • Object
show all
Includes:
ParamTypes
Defined in:
lib/tty/option/parser/keywords.rb

Constant Summary collapse

KEYWORD_ARG_RE =
/([^=-].*?)=([^=]+)/.freeze

Constants included from ParamTypes

ParamTypes::ARGUMENT_PARAMETER, ParamTypes::ENV_VAR_PARAMETER, ParamTypes::KEYWORD_PARAMETER, ParamTypes::OPTION_PARAMETER

Instance Method Summary collapse

Methods included from ParamTypes

#argument?, #env_var?, #keyword?, #option?

Constructor Details

#initialize(keywords, check_invalid_params: true, raise_on_parse_error: false) ⇒ Keywords

Create a command line keywords parser

Parameters:

  • keywords (Array<Keyword>)

    the list of keywords

  • config (Hash)

    the configuration settings



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
50
51
52
53
54
# File 'lib/tty/option/parser/keywords.rb', line 25

def initialize(keywords, check_invalid_params: true,
               raise_on_parse_error: false)
  @keywords = keywords
  @check_invalid_params = check_invalid_params
  @error_aggregator =
    ErrorAggregator.new(raise_on_parse_error: raise_on_parse_error)
  @required_check = RequiredCheck.new(@error_aggregator)
  @arity_check = ArityCheck.new(@error_aggregator)
  @pipeline = Pipeline.new(@error_aggregator)
  @parsed = {}
  @remaining = []
  @names = {}
  @arities = Hash.new(0)

  @keywords.each do |kwarg|
    @names[kwarg.name] = kwarg
    @arity_check << kwarg if kwarg.multiple?

    if kwarg.default?
      case kwarg.default
      when Proc
        assign_keyword(kwarg, kwarg.default.())
      else
        assign_keyword(kwarg, kwarg.default)
      end
    elsif kwarg.required?
      @required_check << kwarg
    end
  end
end

Instance Method Details

#parse(argv) ⇒ Object

Read keyword arguments from the command line



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/tty/option/parser/keywords.rb', line 59

def parse(argv)
  @argv = argv.dup

  loop do
    kwarg, value = next_keyword
    if !kwarg.nil?
      @required_check.delete(kwarg)
      @arities[kwarg.key] += 1

      if block_given?
        yield(kwarg, value)
      end
      assign_keyword(kwarg, value)
    end
    break if @argv.empty?
  end

  @arity_check.(@arities)
  @required_check.()

  [@parsed, @remaining, @error_aggregator.errors]
end