在耙子任务中提出问题

我有一个从另一个rake任务调用的rake任务。

在这个rake任务中,我需要询问用户一些文本input,然后根据答案继续,或者停止一切继续(包括调用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 

HighLinegem使这一切变得简单。

对于一个简单的是或否的问题,你可以使用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 

这是gem的描述:

HighLine对象是input输出stream上的“高级面向行”的shell。 HighLine简化了常用的控制台交互,有效地replaceputs()和gets()。 用户代码可以简单地指定要问的问题以及有关用户交互的任何细节,然后将其余工作留给HighLine。 当HighLine.ask()返回时,即使HighLine必须多次询问,validation结果,执行范围检查,转换types等,您也会得到所要求的答案。

欲了解更多信息,你可以阅读文档 。

虽然这个问题相当古老,但对于使用外部gem的简单用户input来说,这仍然是一个有趣的(也许是已知的)select:

 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