Is it possible to make an interactive Rake task?

后端 未结 4 1548
盖世英雄少女心
盖世英雄少女心 2021-01-31 14:21

I want to run a Rake task that asks the user for input.

I know that I can supply input on the command line, but I want to ask the user if they are sure they wa

4条回答
  •  失恋的感觉
    2021-01-31 14:54

    A handy feature for user input is to put it in a do..while loop, to only continue when a user has supplied valid input. Ruby doesn't explicitly have this construct, but you can achieve the same thing with begin and until. That would add to the accepted answer as follows:

    task :action do
      STDOUT.puts "I'm acting!"
    end
    
    task :check do
      # Loop until the user supplies a valid option
      begin
        STDOUT.puts "Are you sure? (y/n)"
        input = STDIN.gets.strip.downcase
      end until %w(y n).include?(input)
    
      if input == 'y'
        Rake::Task["action"].reenable
        Rake::Task["action"].invoke
      else
        # We know at this point that they've explicitly said no, 
        # rather than fumble the keyboard
        STDOUT.puts "So sorry for the confusion"
      end
    end
    

提交回复
热议问题