Class: Clin::ShellInteraction::Choose

Inherits:
Clin::ShellInteraction show all
Defined in:
lib/clin/shell_interaction/choose.rb

Overview

Handle a choose question

Direct Known Subclasses

Select

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, allow_initials: false) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/clin/shell_interaction/choose.rb', line 50

def choice_help(choices, allow_initials: false)
  used_initials = Set.new
  Clin::Text.new do |t|
    t.line 'Choose from:'
    t.table(indent: 2, border: false, separate_blank: false) do |m|
      m.column_delimiter(allow_initials ? [' - ', '  '] : ['  '])
      choices.each do |choice, description|
        if allow_initials
          inital = used_initials.add?(choice[0]) ? choice[0] : nil
          m.row inital, choice.to_s, description
        else
          m.row choice.to_s, description
        end
      end
    end
  end
end

#run(statement, choices, default: nil, allow_initials: false) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/clin/shell_interaction/choose.rb', line 6

def run(statement, choices, default: nil, allow_initials: false)
  choices = convert_choices(choices)
  question = prepare_question(statement, choices, default: default, initials: allow_initials)
  loop do
    answer = @shell.ask(question, default: default, autocomplete: choices.keys)
    unless answer.nil?
      choices.each do |choice, _|
        if choice.casecmp(answer) == 0 || (allow_initials && choice[0].casecmp(answer[0]) == 0)
          return choice
        end
      end
    end
    print_choices_help(choices, allow_initials: allow_initials)
  end
end