Module: CLI::UI::Prompt

Extended by:
T::Sig
Defined in:
lib/cli/ui/prompt.rb,
lib/cli/ui/prompt/options_handler.rb,
lib/cli/ui/prompt/interactive_options.rb

Defined Under Namespace

Classes: InteractiveOptions, OptionsHandler

Class Method Summary collapse

Methods included from T::Sig

sig

Class Method Details

.ask(question, options: nil, default: nil, is_file: false, allow_empty: true, multiple: false, filter_ui: true, select_ui: true, &options_proc) ⇒ Object


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/cli/ui/prompt.rb', line 112

def ask(
  question,
  options: nil,
  default: nil,
  is_file: false,
  allow_empty: true,
  multiple: false,
  filter_ui: true,
  select_ui: true,
  &options_proc
)
  has_options = !!(options || block_given?)
  if has_options && default && !multiple
    raise(ArgumentError, 'conflicting arguments: default may not be provided with options when not multiple')
  end

  if has_options && is_file
    raise(ArgumentError, 'conflicting arguments: is_file is only useful when options are not provided')
  end

  if options && multiple && default && !(Array(default) - options).empty?
    raise(ArgumentError, 'conflicting arguments: default should only include elements present in options')
  end

  if multiple && !has_options
    raise(ArgumentError, 'conflicting arguments: options must be provided when multiple is true')
  end

  if !multiple && default.is_a?(Array)
    raise(ArgumentError, 'conflicting arguments: multiple defaults may only be provided when multiple is true')
  end

  if has_options
    ask_interactive(
      question,
      options,
      multiple: multiple,
      default: default,
      filter_ui: filter_ui,
      select_ui: select_ui,
      &options_proc
    )
  else
    ask_free_form(question, T.cast(default, T.nilable(String)), is_file, allow_empty)
  end
end

.ask_password(question) ⇒ Object


167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/cli/ui/prompt.rb', line 167

def ask_password(question)
  require 'io/console'

  STDOUT.print(CLI::UI.fmt('{{?}} ' + question)) # Do not use puts_question to avoid the new line.

  # noecho interacts poorly with Readline under system Ruby, so do a manual `gets` here.
  # No fancy Readline integration (like echoing back) is required for a password prompt anyway.
  password = STDIN.noecho do
    # Chomp will remove the one new line character added by `gets`, without touching potential extra spaces:
    # " 123 \n".chomp => " 123 "
    T.must(STDIN.gets).chomp
  end

  STDOUT.puts # Complete the line

  password
end

.confirm(question, default: true) ⇒ Object


196
197
198
# File 'lib/cli/ui/prompt.rb', line 196

def confirm(question, default: true)
  ask_interactive(question, default ? ['yes', 'no'] : ['no', 'yes'], filter_ui: false) == 'yes'
end