Asking questions in rake tasks

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

i think that should work


The HighLine gem makes this easy.

For a simple yes or no question you can use agree:

require "highline/import"
task :agree do
  if agree("Shall we continue? ( yes or no )")
    puts "Ok, lets go"
  else
    puts "Exiting"
  end
end

If you want to do something more complex use 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

Here's the gem's description:

A HighLine object is a "high-level line oriented" shell over an input and an output stream. HighLine simplifies common console interaction, effectively replacing puts() and gets(). User code can simply specify the question to ask and any details about user interaction, then leave the rest of the work to HighLine. When HighLine.ask() returns, you‘ll have the answer you requested, even if HighLine had to ask many times, validate results, perform range checking, convert types, etc.

For more information you can read the docs.


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 

Tags:

Ruby

Rake