Class: Clin::ShellInteraction::Select

Inherits:
Choose show all
Defined in:
lib/clin/shell_interaction/select.rb

Overview

Handle a choose question. Where you select the choices with a number $ Choose:

  1. Choice A

  2. Choice B

  3. Choice B

Instance Attribute Summary

Attributes inherited from Clin::ShellInteraction

#shell

Instance Method Summary collapse

Methods inherited from Clin::ShellInteraction

#initialize, #persist!, #persist?, #persist_answer

Constructor Details

This class inherits a constructor from Clin::ShellInteraction

Instance Method Details

#choice_help(choices, start_index) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/clin/shell_interaction/select.rb', line 23

def choice_help(choices, start_index)
  Clin::Text::Table.new(border: false, col_delim: ' ') do |t|
    i = start_index
    choices.each do |key, description|
      key = "#{key}," unless description.blank?
      row = ["#{i}.", key]
      row << description unless description.blank?
      t.row row
      i += 1
    end
  end
end

#get_choice(choices, answer, start_index) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/clin/shell_interaction/select.rb', line 36

def get_choice(choices, answer, start_index)
  i = start_index
  choices.each do |choice, _|
    return choice if choice.casecmp(answer) == 0 || i.to_s == answer
    i += 1
  end
  nil
end

#run(statement, choices, default: nil, start_index: 1) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/clin/shell_interaction/select.rb', line 11

def run(statement, choices, default: nil, start_index: 1)
  choices = convert_choices(choices)
  loop do
    shell.say statement
    shell.say choice_help(choices, start_index)
    answer = @shell.ask('>', default: default, autocomplete: choices.keys)
    next if answer.nil?
    choice = get_choice(choices, answer, start_index)
    return choice unless choice.nil?
  end
end