Sha256: 792bf84efef11e76125eaaf9a9d03d2a262960ceec80f45f06eabe3a6c20d835

Contents?: true

Size: 1.2 KB

Versions: 1

Compression:

Stored size: 1.2 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
      @default = if (index = @options.keys.index(@default))
        index + 1
      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

    # standard:disable Style/TrivialAccessors
    def options(options)
      @options = options
    end
    # standard:enable Style/TrivialAccessors

    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]
      key
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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