ruby 在rake任务中提问

vsikbqxv  于 12个月前  发布在  Ruby
关注(0)|答案(5)|浏览(99)

我有一个从另一个rake任务调用的rake任务。
在这个rake任务中,我需要请求用户输入一些文本,然后根据答案继续,或者停止一切(包括调用rake任务)。
我该怎么做?

tsm1rwdh

tsm1rwdh1#

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

我想应该可以

z6psavjg

z6psavjg2#

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
14ifxucb

14ifxucb3#

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

下面是gem的描述:
HighLine对象是输入和输出流上的“高级面向行”shell。HighLine简化了常见的控制台交互,有效地取代了puts()和gets()。用户代码可以简单地指定要询问的问题和关于用户交互的任何细节,然后将其余的工作留给HighLine。当HighLine.ask()返回时,即使HighLine必须多次询问、验证结果、执行范围检查、转换类型等,也会得到所请求的答案。
如需了解更多信息,请访问read the docs

siv3szwd

siv3szwd4#

虽然这个问题已经很老了,但这可能仍然是一个有趣的(也许鲜为人知的)替代简单提示而无需外部宝石:

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
bwleehnv

bwleehnv5#

你可以按照上面的建议,内联:

input = ''
  STDOUT.puts "Are you sure you want to continue?(Y/n)"
  input = STDIN.gets.chomp
  abort "aborting" unless input == "Y"

相关问题