-
-
Save botimer/2891186 to your computer and use it in GitHub Desktop.
# This is a reasonably well-behaved helper for command-line scripts needing to ask a simple yes/no question. | |
# It optionally accepts a prompt and a default answer that will be returned on enter keypress. | |
# It keeps asking and echoes the answer on the same line until it gets y/n/Y/N or enter. | |
# I tried to get Highline to behave like this directly, but even though it's sophisticated, I didn't like the result. | |
# This isn't especially elegant, but it is straightforward and gets the job done. | |
require 'highline/import' | |
def yesno(prompt = 'Continue?', default = true) | |
a = '' | |
s = default ? '[Y/n]' : '[y/N]' | |
d = default ? 'y' : 'n' | |
until %w[y n].include? a | |
a = ask("#{prompt} #{s} ") { |q| q.limit = 1; q.case = :downcase } | |
a = d if a.length == 0 | |
end | |
a == 'y' | |
end | |
puts yesno("Do it?", true) |
I don't know if this was in HighLine when the above answers were posted, but this is now even easier:
exit unless HighLine.agree('This will drop the User table. Do you want to proceed?')
if you don't want to use highline and your shell supports it, you could also do something like this:
printf "\033[31mWARNING - press 'y' to continue: "
prompt = STDIN.gets.chomp
return unless prompt == 'y'
@lfender6445 This red colour thing is buggy - it is not ended properly. At least on Linux, on interupted/crashed progams it will stay in terminal (untested in other situations).
@matkoniecz, cause format wasn't cleared. For those to come:
The printf "\033[31mWARNING - press 'y' to continue: "
should be:
The printf "\033[31mWARNING - press 'y' to continue: \033[0m"
if you want red color only in the message.
FYI \e
also works as shorthand for \033
printf "\e[31m#{question} - press 'y' to continue: \e[0m"
You can also just do
puts "press 'y' to continue:".red
If you do what @tweissin-pillpack suggests, you'll also want to require 'colored'
I used this instead: