Module: Bauk::Utils::UserInput
- Defined in:
- lib/bauk/utils/user_input.rb
Overview
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.
Instance Method Summary collapse
- #ask(question, options, map = {}) ⇒ Object
- #askYN(question, default = nil) ⇒ Object
-
#user_input(question, map = {}) ⇒ Object
This def needs to be kept inside Data to prevent a circular dependency.
Instance Method Details
#ask(question, options, map = {}) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/bauk/utils/user_input.rb', line 28 def ask(question, , map = {}) map.default_value(max_tries: 5) question << " [#{map[:default]}]" if map.key? :default question << ' :' if .is_a? Array = .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) .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:' .each { |o, a| puts " - #{o} #{a.empty? ? '' : ": #{a.join ', '}"}" } end raise "Ran out of tries (#{try})." end |
#askYN(question, default = nil) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 |
# 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 = {}) ⇒ Object
This def needs to be kept inside Data to prevent a circular dependency
57 58 59 |
# File 'lib/bauk/utils/user_input.rb', line 57 def user_input(question, map = {}) data.user_input(question, map) end |