Module: EverydayCliUtils::Ask

Defined in:
lib/everyday-cli-utils/ask.rb

Class Method Summary collapse

Class Method Details

.ask(question, options, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/everyday-cli-utils/ask.rb', line 13

def self.ask(question, options, &block)
  val = '-1'
  loop do
    print "#{question}\n\n#{setup_options(options)}\n\n"
    val = Readline.readline("Please enter your choice (1 - #{options.count}): ", true)
    break if !(val =~ /^\d+$/).nil? && (1..options.count).include?(val.to_i)
    print "\n\nYou must enter an integer between 1 and #{options.count}. Please try again.\n\n"
  end
  block.call(options[val.to_i - 1])
end

.ask_prefill(question, prefill) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/everyday-cli-utils/ask.rb', line 30

def self.ask_prefill(question, prefill)
  old_hook = Readline.pre_input_hook
  Readline.pre_input_hook =-> {
    Readline.insert_text(prefill)
    Readline.redisplay
  }
  rval = Readline.readline(question, true)
  Readline.pre_input_hook = old_hook
  rval
end

.ask_yn(question, options = {}, &block) ⇒ Object



24
25
26
27
28
# File 'lib/everyday-cli-utils/ask.rb', line 24

def self.ask_yn(question, options = {}, &block)
  resp = Readline.readline("#{question} ([y]es/[n]o) ", true)
  val = resp.downcase == 'yes' || resp.downcase == 'y'
  block.call(val) if !options[:only] || options[:only] == (val ? :yes : :no)
end

.hash_to_options(hash, extra = []) ⇒ Object



41
42
43
# File 'lib/everyday-cli-utils/ask.rb', line 41

def self.hash_to_options(hash, extra = [])
  hash.keys + extra
end

.setup_options(options) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/everyday-cli-utils/ask.rb', line 5

def self.setup_options(options)
  mapped = []
  options.each_with_index { |v, k|
    mapped << "#{k + 1}) #{v}"
  }
  mapped.join("\n")
end