Module: Pechkin::CLIHelper

Included in:
CLI
Defined in:
lib/pechkin/cli.rb

Overview

Helper methods to declare all command line options. This should remove most optparse configuration boilerplate

Instance Method Summary collapse

Instance Method Details



33
34
35
# File 'lib/pechkin/cli.rb', line 33

def banner(banner)
  @cli_banner = banner
end

#opt(name, names:, default: nil, desc: '', type: nil) ⇒ Object

Parameters:

  • name (Symbol)

    variable name to store values



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/pechkin/cli.rb', line 16

def opt(name, names:, default: nil, desc: '', type: nil)
  @cli_options ||= []

  # raise ':names is nil or empty' if names.nil? || names.empty?

  @cli_options << { name: name,
                    default: default,
                    names: names,
                    type: type,
                    desc: desc }
end

#parse(args) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/pechkin/cli.rb', line 37

def parse(args)
  values = OpenStruct.new
  parser = parser_create(values)

  parser.parse(args)
  new.post_init(values)
end

#parser_create(values) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/pechkin/cli.rb', line 45

def parser_create(values)
  parser = OptionParser.new
  parser.banner = @cli_banner

  (@cli_options || []).each do |o|
    if o.is_a?(String)
      parser.separator o
    else
      values[o[:name]] = o[:default] if o[:default]

      args = []
      args += o[:names]
      args << o[:type] if o[:type]
      args << o[:desc] if o[:desc]

      parser.on(*args) { |v| values[o[:name]] = v }
    end
  end

  parser_create_default_opts(parser)

  parser
end

#parser_create_default_opts(parser) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/pechkin/cli.rb', line 69

def parser_create_default_opts(parser)
  parser.separator ''
  parser.separator 'Common options:'
  parser.on_tail('-h', '--help', 'Show this message') do
    puts parser
    exit 1
  end

  # Another typical switch to print the version.
  parser.on_tail('--version', 'Show version') do
    puts Version.version_string
    exit 0
  end
end

#separator(string) ⇒ Object



28
29
30
31
# File 'lib/pechkin/cli.rb', line 28

def separator(string)
  @cli_options ||= []
  @cli_options << string
end