Class: PDK::CLI::Util::Interview

Inherits:
TTY::Prompt::AnswersCollector
  • Object
show all
Defined in:
lib/pdk/cli/util/interview.rb

Constant Summary collapse

READER =
defined?(TTY::Reader) ? TTY::Reader : TTY::Prompt::Reader

Instance Method Summary collapse

Constructor Details

#initialize(prompt, options = {}) ⇒ Interview

Override the initialize method because the original one doesn’t work with Ruby 3. rubocop:disable Lint/MissingSuper



13
14
15
16
# File 'lib/pdk/cli/util/interview.rb', line 13

def initialize(prompt, options = {})
  @prompt  = prompt
  @answers = options.fetch(:answers) { {} }
end

Instance Method Details

#add_question(options = {}) ⇒ Object



29
30
31
# File 'lib/pdk/cli/util/interview.rb', line 29

def add_question(options = {})
  (@questions ||= {})[options[:name]] = options
end

#add_questions(questions) ⇒ Object



23
24
25
26
27
# File 'lib/pdk/cli/util/interview.rb', line 23

def add_questions(questions)
  questions.each do |question|
    add_question(question)
  end
end

#num_questionsObject



33
34
35
# File 'lib/pdk/cli/util/interview.rb', line 33

def num_questions
  (@questions ||= {}).count
end

#pastelObject

rubocop:enable Lint/MissingSuper



19
20
21
# File 'lib/pdk/cli/util/interview.rb', line 19

def pastel
  @pastel ||= Pastel.new
end

#runObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/pdk/cli/util/interview.rb', line 37

def run
  i = 1
  num_questions = @questions.count
  @questions.each do |question_name, question|
    @name = question_name
    @prompt.print "#{pastel.bold(format('[Q %{current_number}/%{questions_total}]', current_number: i, questions_total: num_questions))} "
    @prompt.puts pastel.bold(question[:question])
    @prompt.puts question[:help] if question.key?(:help)

    case question[:type]
    when :yes
      yes?('-->') do |q|
        q.default(question[:default]) if question.key?(:default)
      end
    when :multi_select
      multi_select('-->', per_page: question[:choices].count) do |q|
        q.enum ')'
        q.default(*question[:default]) if question.key?(:default)

        question[:choices].each do |text, |
          q.choice text, 
        end
      end
    else
      ask('-->') do |q|
        q.required(question.fetch(:required, false))

        q.validate(question[:validate_pattern], question[:validate_message]) if question.key?(:validate_pattern)

        q.default(question[:default]) if question.key?(:default)
      end
    end
    i += 1
    @prompt.puts ''
  end
  @answers
rescue READER::InputInterrupt
  nil
end