Module: Squared::Common::Prompt
- Defined in:
- lib/squared/common/prompt.rb
Class Method Summary collapse
- .choice(msg, list = nil, min: 1, max: 1, multiple: false, auto: true, force: true, attempts: 5, timeout: 60) ⇒ Object
- .confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 30) ⇒ Object
- .readline(msg, history = false, force: nil) ⇒ Object
Class Method Details
.choice(msg, list = nil, min: 1, max: 1, multiple: false, auto: true, force: true, 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 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/squared/common/prompt.rb', line 35 def choice(msg, list = nil, min: 1, max: 1, multiple: false, auto: true, force: true, 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 if auto msg = "#{msg}: [1-#{max}#{if multiple "|,#{multiple.is_a?(Numeric) ? "{#{multiple}}" : ''}" end}] " end 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)) unless (ch = ch.strip).empty? if multiple a = ch.split(/\s*,\s*/) b = a.select { |s| valid.call(s) }.map!(&:to_i).sort next unless a.size == b.size return b unless items next if multiple.is_a?(::Numeric) && multiple != b.size return b.map! { |i| items[i - 1] } elsif valid.call(ch) return items ? items[ch.to_i - 1] : ch.to_i end end attempts -= 1 next if attempts > 0 break unless force exit 1 end rescue Interrupt puts exit 0 else multiple ? [] : nil end end end |
.confirm(msg, default = nil, agree: 'Y', cancel: 'N', attempts: 5, timeout: 30) ⇒ 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: 30) 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)) 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 |
.readline(msg, history = false, force: nil) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/squared/common/prompt.rb', line 85 def readline(msg, history = false, force: nil) require 'readline' case force when ::TrueClass, ::FalseClass msg = "#{msg} (#{force ? 'required' : 'optional'}): " ret = Readline.readline(msg, history)&.strip || '' raise_error 'user cancelled' if force && ret.empty? ret else Readline.readline(msg, history) end end |