询问任务

问题描述 投票:38回答:4

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

在此rake任务中,我需要询问用户一些文本输入,然后根据答案继续执行,或停止一切继续执行(包括调用rake任务)。

我该怎么做?

ruby rake
4个回答
60
投票
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

我认为应该起作用


10
投票
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 

8
投票

HighLine宝石使此变得容易。

对于简单的是或否问题,您可以使用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要求多次,也可以得到您要求的答案,验证结果,执行范围检查,转换类型等。

有关更多信息,您可以read the docs


2
投票

尽管问题已经很久了,但对于简单用户而言,如果不使用外部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
© www.soinside.com 2019 - 2024. All rights reserved.