Class: TTY::Prompt

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/tty/prompt.rb,
lib/tty/prompt/list.rb,
lib/tty/prompt/choice.rb,
lib/tty/prompt/reader.rb,
lib/tty/prompt/result.rb,
lib/tty/prompt/slider.rb,
lib/tty/prompt/choices.rb,
lib/tty/prompt/symbols.rb,
lib/tty/prompt/timeout.rb,
lib/tty/prompt/version.rb,
lib/tty/prompt/distance.rb,
lib/tty/prompt/expander.rb,
lib/tty/prompt/keypress.rb,
lib/tty/prompt/question.rb,
lib/tty/prompt/enum_list.rb,
lib/tty/prompt/evaluator.rb,
lib/tty/prompt/multiline.rb,
lib/tty/prompt/paginator.rb,
lib/tty/prompt/statement.rb,
lib/tty/prompt/converters.rb,
lib/tty/prompt/multi_list.rb,
lib/tty/prompt/suggestion.rb,
lib/tty/prompt/reader/line.rb,
lib/tty/prompt/reader/mode.rb,
lib/tty/prompt/reader/codes.rb,
lib/tty/prompt/converter_dsl.rb,
lib/tty/prompt/mask_question.rb,
lib/tty/prompt/enum_paginator.rb,
lib/tty/prompt/reader/console.rb,
lib/tty/prompt/reader/history.rb,
lib/tty/prompt/reader/win_api.rb,
lib/tty/prompt/question/checks.rb,
lib/tty/prompt/confirm_question.rb,
lib/tty/prompt/reader/key_event.rb,
lib/tty/prompt/answers_collector.rb,
lib/tty/prompt/question/modifier.rb,
lib/tty/prompt/converter_registry.rb,
lib/tty/prompt/reader/win_console.rb,
lib/tty/prompt/question/validation.rb

Overview

A class responsible for terminal prompt interactions.

Direct Known Subclasses

TestPrompt

Defined Under Namespace

Modules: ConverterDSL, Converters, Symbols Classes: AnswersCollector, Choice, Choices, ConfirmQuestion, ConverterRegistry, Distance, EnumList, EnumPaginator, Evaluator, Expander, Keypress, List, MaskQuestion, MultiList, Multiline, Paginator, Question, Reader, Result, Slider, Statement, Suggestion, Timeout

Constant Summary collapse

ConfigurationError =

Raised when wrong parameter is used to configure prompt

Class.new(StandardError)
ConversionError =

Raised when type conversion cannot be performed

Class.new(StandardError)
ValidationCoercion =

Raised when the passed in validation argument is of wrong type

Class.new(TypeError)
ArgumentRequired =

Raised when the required argument is not supplied

Class.new(ArgumentError)
ArgumentValidation =

Raised when the argument validation fails

Class.new(ArgumentError)
InvalidArgument =

Raised when the argument is not expected

Class.new(ArgumentError)
VERSION =
"0.13.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Prompt

Initialize a Prompt

Parameters:

  • options (Hash)


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/tty/prompt.rb', line 115

def initialize(*args)
  options = Utils.extract_options!(args)
  @input  = options.fetch(:input) { $stdin }
  @output = options.fetch(:output) { $stdout }
  @env    = options.fetch(:env) { ENV }
  @prefix = options.fetch(:prefix) { '' }
  @enabled_color = options[:enable_color]
  @active_color  = options.fetch(:active_color) { :green }
  @help_color    = options.fetch(:help_color)   { :bright_black }
  @error_color   = options.fetch(:error_color)  { :red }
  @interrupt     = options.fetch(:interrupt)    { :error }
  @track_history = options.fetch(:track_history) { true }

  @cursor = TTY::Cursor
  @pastel = Pastel.new(@enabled_color.nil? ? {} : { enabled: @enabled_color })
  @reader = Reader.new(@input, @output, interrupt: @interrupt,
                       track_history: @track_history, env: @env)
end

Instance Attribute Details

#active_colorObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Theme colors



70
71
72
# File 'lib/tty/prompt.rb', line 70

def active_color
  @active_color
end

#cursorObject (readonly)

Returns the value of attribute cursor.



55
56
57
# File 'lib/tty/prompt.rb', line 55

def cursor
  @cursor
end

#enabled_colorObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Theme colors



70
71
72
# File 'lib/tty/prompt.rb', line 70

def enabled_color
  @enabled_color
end

#error_colorObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Theme colors



70
71
72
# File 'lib/tty/prompt.rb', line 70

def error_color
  @error_color
end

#help_colorObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Theme colors



70
71
72
# File 'lib/tty/prompt.rb', line 70

def help_color
  @help_color
end

#inputObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



48
49
50
# File 'lib/tty/prompt.rb', line 48

def input
  @input
end

#outputObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



51
52
53
# File 'lib/tty/prompt.rb', line 51

def output
  @output
end

#prefixString (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Prompt prefix

Examples:

prompt = TTY::Prompt.new(prefix: [?])

Returns:

  • (String)


65
66
67
# File 'lib/tty/prompt.rb', line 65

def prefix
  @prefix
end

#readerObject (readonly)

Returns the value of attribute reader.



53
54
55
# File 'lib/tty/prompt.rb', line 53

def reader
  @reader
end

Class Method Details

.messagesObject



82
83
84
85
86
87
88
# File 'lib/tty/prompt.rb', line 82

def self.messages
  {
    range?: 'Value %{value} must be within the range %{in}',
    valid?: 'Your answer is invalid (must match %{valid})',
    required?: 'Value must be provided'
  }
end

Instance Method Details

#ask(message, *args) {|question| ... } ⇒ TTY::Prompt::Question

Ask a question.

Examples:

propmt = TTY::Prompt.new
prompt.ask("What is your name?")

Parameters:

  • message (String)

    the question to be asked

Yields:

  • (question)

Yield Parameters:

Returns:



167
168
169
# File 'lib/tty/prompt.rb', line 167

def ask(message, *args, &block)
  invoke_question(Question, message, *args, &block)
end

#collect(options = {}, &block) ⇒ Hash

Gathers more than one aswer

Examples:

prompt.collect do
  key(:name).ask('Name?')
end

Returns:

  • (Hash)

    the collection of answers



483
484
485
486
# File 'lib/tty/prompt.rb', line 483

def collect(options = {}, &block)
  collector = AnswersCollector.new(self, options)
  collector.call(&block)
end

#enum_select(question, *args, &block) ⇒ String

Ask a question with indexed list

Examples:

prompt = TTY::Prompt.new
editors = %w(emacs nano vim)
prompt.enum_select(EnumList, "Select editor: ", editors)

Parameters:

  • question (String)

    the question to ask

  • choices (Array[Object])

    the choices to select from

Returns:

  • (String)


293
294
295
# File 'lib/tty/prompt.rb', line 293

def enum_select(question, *args, &block)
  invoke_select(EnumList, question, *args, &block)
end

#error(*args) ⇒ Array

Print statement(s) out in red color.

Examples:

prompt.error "Shutting down all systems!"
prompt.error "Nothing is fine!", "All is broken!"

Parameters:

  • messages (Array)

Returns:

  • (Array)

    messages



440
441
442
443
# File 'lib/tty/prompt.rb', line 440

def error(*args)
  options = Utils.extract_options!(args)
  args.each { |message| say message, options.merge(color: :red) }
end

#expand(message, *args, &block) ⇒ Object

Expand available options

Examples:

prompt = TTY::Prompt.new
choices = [{
  key: 'Y',
  name: 'Overwrite',
  value: :yes
}, {
  key: 'n',
  name: 'Skip',
  value: :no
}]
prompt.expand('Overwirte Gemfile?', choices)

Returns:

  • (Object)

    the user specified value



356
357
358
# File 'lib/tty/prompt.rb', line 356

def expand(message, *args, &block)
  invoke_select(Expander, message, *args, &block)
end

#inspectString

Inspect class name and public attributes

Returns:

  • (String)


522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/tty/prompt.rb', line 522

def inspect
  attributes = {
    input: input,
    output: output,
    prefix: prefix,
    active_color: active_color,
    error_color: error_color,
    enabled_color: enabled_color,
    help_color: help_color
  }
  "#<#{self.class}: #{attributes.each { |name, val| "@#{name}=#{val}" }}"
end

#invoke_question(object, message, *args, &block) ⇒ String

Invoke a question type of prompt

Examples:

prompt = TTY::Prompt.new
prompt.invoke_question(Question, "Your name? ")

Returns:

  • (String)


143
144
145
146
147
148
# File 'lib/tty/prompt.rb', line 143

def invoke_question(object, message, *args, &block)
  options = Utils.extract_options!(args)
  options[:messages] = self.class.messages
  question = object.new(self, options)
  question.(message, &block)
end

#invoke_select(object, question, *args, &block) ⇒ String

Invoke a list type of prompt

Examples:

prompt = TTY::Prompt.new
editors = %w(emacs nano vim)
prompt.invoke_select(EnumList, "Select editor: ", editors)

Returns:

  • (String)


202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/tty/prompt.rb', line 202

def invoke_select(object, question, *args, &block)
  options = Utils.extract_options!(args)
  choices = if block
              []
            elsif args.empty?
              possible = options.dup
              options = {}
              possible
            elsif args.size == 1 && args[0].is_a?(Hash)
              Utils.extract_options!(args)
            else
              args.flatten
            end

  list = object.new(self, options)
  list.(question, choices, &block)
end

#keypress(message, *args, &block) ⇒ Object

Ask a question with a keypress answer

See Also:



176
177
178
# File 'lib/tty/prompt.rb', line 176

def keypress(message, *args, &block)
  invoke_question(Keypress, message, *args, &block)
end

#mask(message, *args, &block) ⇒ TTY::Prompt::MaskQuestion

Ask masked question

Examples:

propmt = TTY::Prompt.new
prompt.mask("What is your secret?")

Returns:



229
230
231
# File 'lib/tty/prompt.rb', line 229

def mask(message, *args, &block)
  invoke_question(MaskQuestion, message, *args, &block)
end

#multi_select(question, *args, &block) ⇒ String

Ask a question with multiple attributes activated

Examples:

prompt = TTY::Prompt.new
choices = %w(Scorpion Jax Kitana Baraka Jade)
prompt.multi_select("Choose your destiny?", choices)

Parameters:

  • question (String)

    the question to ask

  • choices (Array[Object])

    the choices to select from

Returns:

  • (String)


273
274
275
# File 'lib/tty/prompt.rb', line 273

def multi_select(question, *args, &block)
  invoke_select(MultiList, question, *args, &block)
end

#multiline(message, *args, &block) ⇒ Array[String]

Ask a question with a multiline answer

Examples:

prompt.multiline('Description?')

Returns:

  • (Array[String])


188
189
190
# File 'lib/tty/prompt.rb', line 188

def multiline(message, *args, &block)
  invoke_question(Multiline, message, *args, &block)
end

#no?(message, *args, &block) ⇒ Boolean

A shortcut method to ask the user negative question and return true for ‘no’ reply.

Examples:

prompt = TTY::Prompt.new
prompt.no?('Are you alien?') # => true
# => Are you human? (y/N)

Returns:

  • (Boolean)


328
329
330
331
332
333
334
335
# File 'lib/tty/prompt.rb', line 328

def no?(message, *args, &block)
  defaults = { default: false }
  options  = Utils.extract_options!(args)
  options.merge!(defaults.reject { |k, _| options.key?(k) })

  question = ConfirmQuestion.new(self, options)
  !question.call(message, &block)
end

#ok(*args) ⇒ Array

Print statement(s) out in red green.

Examples:

prompt.ok "Are you sure?"
prompt.ok "All is fine!", "This is fine too."

Parameters:

  • messages (Array)

Returns:

  • (Array)

    messages



408
409
410
411
# File 'lib/tty/prompt.rb', line 408

def ok(*args)
  options = Utils.extract_options!(args)
  args.each { |message| say message, options.merge(color: :green) }
end

#say(message = '', options = {}) ⇒ String

Print statement out. If the supplied message ends with a space or tab character, a new line will not be appended.

Examples:

say("Simple things.", color: :red)

Parameters:

  • message (String) (defaults to: '')

Returns:

  • (String)


389
390
391
392
393
394
395
# File 'lib/tty/prompt.rb', line 389

def say(message = '', options = {})
  message = message.to_s
  return if message.empty?

  statement = Statement.new(self, options)
  statement.call(message)
end

#select(question, *args, &block) ⇒ Object

Ask a question with a list of options

Examples:

prompt = TTY::Prompt.new
prompt.select("What size?", %w(large medium small))
prompt = TTY::Prompt.new
prompt.select("What size?") do |menu|
  menu.choice :large
  menu.choices %w(:medium :small)
end

Parameters:

  • question (String)

    the question to ask

  • choices (Array[Object])

    the choices to select from



253
254
255
# File 'lib/tty/prompt.rb', line 253

def select(question, *args, &block)
  invoke_select(List, question, *args, &block)
end

#slider(question, *args, &block) ⇒ String

Ask a question with a range slider

Examples:

prompt = TTY::Prompt.new
prompt.slider('What size?', min: 32, max: 54, step: 2)

Parameters:

  • question (String)

    the question to ask

Returns:

  • (String)


372
373
374
375
376
# File 'lib/tty/prompt.rb', line 372

def slider(question, *args, &block)
  options = Utils.extract_options!(args)
  slider = Slider.new(self, options)
  slider.call(question, &block)
end

#stderrObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return standard error



514
515
516
# File 'lib/tty/prompt.rb', line 514

def stderr
  $stderr
end

#stdinObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return standard in



500
501
502
# File 'lib/tty/prompt.rb', line 500

def stdin
  $stdin
end

#stdoutObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return standard out



507
508
509
# File 'lib/tty/prompt.rb', line 507

def stdout
  $stdout
end

#suggest(message, possibilities, options = {}) ⇒ String

Takes the string provided by the user and compare it with other possible matches to suggest an unambigous string

Examples:

prompt.suggest('sta', ['status', 'stage', 'commit', 'branch'])
# => "status, stage"

Parameters:

  • message (String)
  • possibilities (Array)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :indent (String)

    The number of spaces for indentation

  • :single_text (String)

    The text for a single suggestion

  • :plural_text (String)

    The text for multiple suggestions

Returns:

  • (String)


467
468
469
470
# File 'lib/tty/prompt.rb', line 467

def suggest(message, possibilities, options = {})
  suggestion = Suggestion.new(options)
  say(suggestion.suggest(message, possibilities))
end

#tty?Boolean

Check if outputing to terminal

Returns:

  • (Boolean)


493
494
495
# File 'lib/tty/prompt.rb', line 493

def tty?
  stdout.tty?
end

#warn(*args) ⇒ Array

Print statement(s) out in yellow color.

Examples:

prompt.warn "This action can have dire consequences"
prompt.warn "Carefull young apprentice", "This is potentially dangerous"

Parameters:

  • messages (Array)

Returns:

  • (Array)

    messages



424
425
426
427
# File 'lib/tty/prompt.rb', line 424

def warn(*args)
  options = Utils.extract_options!(args)
  args.each { |message| say message, options.merge(color: :yellow) }
end

#yes?(message, *args, &block) ⇒ Boolean

A shortcut method to ask the user positive question and return true for ‘yes’ reply, false for ‘no’.

Examples:

prompt = TTY::Prompt.new
prompt.yes?('Are you human?')
# => Are you human? (Y/n)

Returns:

  • (Boolean)


308
309
310
311
312
313
314
315
# File 'lib/tty/prompt.rb', line 308

def yes?(message, *args, &block)
  defaults = { default: true }
  options  = Utils.extract_options!(args)
  options.merge!(defaults.reject { |k, _| options.key?(k) })

  question = ConfirmQuestion.new(self, options)
  question.call(message, &block)
end