module Bauk::Utils::UserInput
This mixin is used to allow user input through a series of methods. It relies upon Data as it uses the interactive mode to decide whether to
throw an error/return default value if present, or ask user for input.
Public Instance Methods
ask(question, options, map = {})
click to toggle source
# File lib/bauk/utils/user_input.rb, line 28 def ask(question, options, map = {}) map.default_value(max_tries: 5) question << " [#{map[:default]}]" if map.key? :default question << ' :' if options.is_a? Array options = options.map do |o| [o, []] end.to_h end try = 0 while map[:max_tries] != try # So if 0 is passed, it goes indefinitely try += 1 ans = user_input(question) options.each do |option, aliases| return option if ans == option || ans =~ /^#{option}$/ aliases.each do |a| return option if ans =~ /^#{a}$/ end end return map[:default] if map.key?(:default) && ans == '' puts 'Options:' options.each { |o, a| puts " - #{o} #{a.empty? ? '' : ": #{a.join ', '}"}" } end raise "Ran out of tries (#{try})." end
askYN(question, default = nil)
click to toggle source
# File lib/bauk/utils/user_input.rb, line 15 def askYN(question, default = nil) default = data.get_with_default(:default_yn, nil) if default.nil? loop do ans = user_input("#{question} y/n #{case default when true then '[y]' when false then '[n]' end}: ", default: default) return default if (ans == '') && !default.nil? return true if /^y(es)*$/i =~ ans return false if /^n(o)*$/i =~ ans end end
user_input(question, map = {})
click to toggle source
This def needs to be kept inside Data to prevent a circular dependency
# File lib/bauk/utils/user_input.rb, line 57 def user_input(question, map = {}) data.user_input(question, map) end
Private Instance Methods
data()
click to toggle source
# File lib/bauk/utils/user_input.rb, line 63 def data @data ||= Data.instance @data end