Module: Doing::PromptYN

Included in:
Prompt
Defined in:
lib/doing/prompt/yn.rb

Overview

Request Yes/No answers on command line

Instance Method Summary collapse

Instance Method Details

#yn(question, default_response: false) ⇒ Boolean

Ask a yes or no question in the terminal

Parameters:

  • question (String)

    The question to ask

  • default_response (Boolean) (defaults to: false)

    default response if no input

Returns:

  • (Boolean)

    yes or no



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/doing/prompt/yn.rb', line 16

def yn(question, default_response: false)
  return @force_answer == :yes ? true : false unless @force_answer.nil?

  $stdin.reopen('/dev/tty')

  default = if default_response.is_a?(String)
              default_response =~ /y/i ? true : false
            else
              default_response
            end

  # if global --default is set, answer default
  return default if @default_answer

  # if this isn't an interactive shell, answer default
  return default unless $stdout.isatty

  # clear the buffer
  if ARGV&.length
    ARGV.length.times do
      ARGV.shift
    end
  end
  system 'stty cbreak'

  cw = white
  cbw = boldwhite
  cbg = boldgreen
  cd = Color.default

  options = unless default.nil?
              "#{cw}[#{default ? "#{cbg}Y#{cw}/#{cbw}n" : "#{cbw}y#{cw}/#{cbg}N"}#{cw}]#{cd}"
            else
              "#{cw}[#{cbw}y#{cw}/#{cbw}n#{cw}]#{cd}"
            end
  $stdout.syswrite "#{cbw}#{question.sub(/\?$/, '')} #{options}#{cbw}?#{cd} "
  res = $stdin.sysread 1
  puts
  system 'stty cooked'

  res.chomp!
  res.downcase!

  return default if res.empty?

  res =~ /y/i ? true : false
end