[英]Asking questions in rake tasks
我有一个从另一个 rake 任务调用的 rake 任务。
在这个 rake 任务中,我需要要求用户输入一些文本,然后根据答案继续或停止所有内容(包括调用 rake 任务)。
我怎样才能做到这一点?
task :input_test do
input = ''
STDOUT.puts "What is the airspeed velocity of a swallow?"
input = STDIN.gets.chomp
raise "bah, humbug!" unless input == "an african or european swallow?"
end
task :blah_blah => :input_test do
end
我认为这应该有效
task :ask_question do
puts "Do you want to go through with the task(Y/N)?"
get_input
end
task :continue do
puts "Task starting..."
# the task is executed here
end
def get_input
STDOUT.flush
input = STDIN.gets.chomp
case input.upcase
when "Y"
puts "going through with the task.."
Rake::Task['continue'].invoke
when "N"
puts "aborting the task.."
else
puts "Please enter Y or N"
get_input
end
end
HighLine gem 让这一切变得简单。
对于简单的是或否问题,您可以使用agree
:
require "highline/import"
task :agree do
if agree("Shall we continue? ( yes or no )")
puts "Ok, lets go"
else
puts "Exiting"
end
end
如果你想做一些更复杂的事情,请使用ask
:
require "highline/import"
task :ask do
answer = ask("Go left or right?") { |q|
q.default = "left"
q.validate = /^(left|right)$/i
}
if answer.match(/^right$/i)
puts "Going to the right"
else
puts "Going to the left"
end
end
这是宝石的描述:
HighLine 对象是输入和输出流上的“高级面向行”外壳。 HighLine 简化了常见的控制台交互,有效地替换了 puts() 和 gets()。 用户代码可以简单地指定要问的问题和有关用户交互的任何详细信息,然后将其余工作留给 HighLine。 当 HighLine.ask() 返回时,您将得到您请求的答案,即使 HighLine 必须多次询问、验证结果、执行范围检查、转换类型等。
有关更多信息,您可以阅读文档。
尽管这个问题已经很老了,但对于没有外部 gem 的简单提示,这可能仍然是一个有趣的(也许鲜为人知的)替代方案:
require 'rubygems/user_interaction'
include Gem::UserInteraction
task :input_test do
input = ask("What is the airspeed velocity of a swallow?")
raise "bah, humbug!" unless input == "an african or european swallow?"
end
task :blah_blah => :input_test do
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.