Module: Squared::Common::Prompt

Defined in:
lib/squared/common/prompt.rb

Class Method Summary collapse

Class Method Details

.confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 15) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/squared/common/prompt.rb', line 8

def confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 15)
  require 'readline'
  require 'timeout'
  agree = /\A#{agree}\z/i if agree.is_a?(::String)
  cancel = /\A#{cancel}\z/i if cancel.is_a?(::String)
  Timeout.timeout(timeout) do
    begin
      while (ch = Readline.readline(msg, true))
        ch = ch.chomp
        case (ch.empty? ? default : ch)
        when agree
          return true
        when cancel
          return false
        end
        attempts -= 1
        exit 1 unless attempts > 0
      end
    rescue Interrupt
      puts
      exit 0
    else
      false
    end
  end
end