Module: Squared::Common::Prompt

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

Class Method Summary collapse

Class Method Details

.choice(msg, list = nil, min: 1, max: 1, multiple: false, attempts: 5, timeout: 60) ⇒ Object



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
63
64
65
66
67
68
69
70
71
# File 'lib/squared/common/prompt.rb', line 35

def choice(msg, list = nil, min: 1, max: 1, multiple: false, attempts: 5, timeout: 60)
  require 'readline'
  require 'timeout'
  if list
    items = []
    list.each_with_index do |val, index|
      puts "#{index.succ.to_s.rjust(2)}. #{val}"
      items << val.chomp
    end
    max = items.size
    msg = "#{msg}: [1-#{max}#{multiple ? '|,' : ''}] "
  end
  return unless max >= min

  valid = ->(s) { s.match?(/^-?\d+$/) && s.to_i.between?(min, max) }
  Timeout.timeout(timeout) do
    begin
      while (ch = Readline.readline(msg, true))
        ch = ch.strip
        if multiple
          a = ch.split(/\s*,\s*/)
          b = a.select { |s| valid.call(s) }.map!(&:to_i)
          return items ? b.map! { |i| items[i - 1] } : b if a.size == b.size
        elsif valid.call(ch)
          return items ? items[ch.to_i - 1] : ch.to_i
        end
        attempts -= 1
        exit 1 unless attempts > 0
      end
    rescue Interrupt
      puts
      exit 0
    else
      multiple ? [] : nil
    end
  end
end

.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 = /^#{agree}$/i if agree.is_a?(::String)
  cancel = /^#{cancel}$/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