Sha256: 988fd9f0f8ab8369a49cb1259bfa08753ee906964a62659d711ff3cb17bcbc90

Contents?: true

Size: 1.15 KB

Versions: 1

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

module Prompts
  class SelectPrompt < Prompt
    def self.ask(options: nil, **kwargs)
      instance = new(options: options, **kwargs)
      yield instance if block_given?
      instance.ask
    end

    def initialize(options: nil, **kwargs)
      super(**kwargs)

      @options = options.is_a?(Array) ? options.to_h { |item| [item, item] } : options
      if (index = @options.keys.index(@default))
        @default = index + 1
      else
        @default = nil
      end
      @instructions = "Enter the number of your choice"
      @hint ||= "Type your response and press Enter ⏎"
      @validations << ->(choice) { "Invalid choice." if !choice.to_i.between?(1, @options.size) }
    end

    def options(options)
      @options = options
    end

    def prepare_content
      super
      @options.each_with_index do |(key, value), index|
        @content.paragraph Fmt("%{prefix}faint|bold %{option}", prefix: "#{index + 1}.", option: value)
      end
      @content
    end

    private

      def resolve_choice_from(response)
        choice = response.to_i
        key, value = @options.to_a[choice - 1]
        value
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prompts-0.2.0 lib/prompts/select_prompt.rb