Skip to content

Instantly share code, notes, and snippets.

@yaauie
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaauie/86d854cb3e2ad40aab24 to your computer and use it in GitHub Desktop.
Save yaauie/86d854cb3e2ad40aab24 to your computer and use it in GitHub Desktop.
# 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