Last active
August 29, 2015 14:01
-
-
Save yaauie/86d854cb3e2ad40aab24 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get reasonable CLI confirmation before continuing. | |
# | |
# @param text [String] - the descriptive text | |
# @param options [Hash{Symbol=>Object}] | |
# @option options [Boolean] :default - the default action (false) | |
# @option options [#puts] :out - the IO on which to puts output ($stderr) | |
# @option options [#readline] :in - the IO on which to readline input ($stdin) | |
# @option options [String] :prompt - the prompt string ("ok?") | |
# | |
# @example | |
# ~~~ ruby | |
# if confirm?('This action is destructive', default: true, prompt: 'do it anyway?') | |
# dangerous_thing! | |
# else | |
# return false | |
# end | |
# ~~~ | |
def confirm?(text, options={}) | |
default = options.fetch(:default, false) | |
output = options.fetch(:out, $stderr) | |
input = options.fetch(:in, $stdin) | |
prompt = options.fetch(:prompt, 'ok?') | |
output.puts text | |
loop do | |
output.puts "#{prompt} #{default ? '(Y/n)' : '(y/N)'}:" | |
received = input.readline | |
case | |
when received.chomp.empty? | |
return default | |
when received =~ /^y(es)?$/i | |
return true | |
when received =~ /^n(o)?$/i | |
return false | |
else | |
output.puts('input not understood. Please type "yes" or "no".') | |
next | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment