Sha256: 9f6adc7a5ca4bbfa4264ab88111a1bc960335c9983bee2851e514d68daf11cae

Contents?: true

Size: 1.99 KB

Versions: 3

Compression:

Stored size: 1.99 KB

Contents

require 'tty-prompt'

module PDK
  module CLI
    module Util
      class Interview < TTY::Prompt::AnswersCollector
        def pastel
          @pastel ||= Pastel.new
        end

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

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

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

        def run
          i = 1
          num_questions = @questions.count
          @questions.each do |question_name, question|
            @name = question_name
            @prompt.print pastel.bold(_('[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, metadata|
                  q.choice text, metadata
                end
              end
            else
              ask(_('-->')) do |q|
                q.required(question.fetch(:required, false))

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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pdk-1.12.0 lib/pdk/cli/util/interview.rb
pdk-1.11.1 lib/pdk/cli/util/interview.rb
pdk-1.11.0 lib/pdk/cli/util/interview.rb