Is it possible to make an interactive Rake task?

后端 未结 4 1549
盖世英雄少女心
盖世英雄少女心 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:58

    You could also wrap this up in a service class so it can be unit-tested and used across your rake tasks:

    # frozen_string_literal: true
    
    class RakeConfirmDialog
      def initialize(question)
        @question = "#{question} (y/n)"
        @answer = "".inquiry
      end
    
      def confirm!
        prompt until (proceed? || abort?)
    
        respond
    
        proceed?
      end
    
      private
    
      def prompt
        STDOUT.puts @question
    
        @answer = STDIN.gets.strip.downcase.inquiry
      end
    
      def respond
        STDOUT.puts proceed? ? "Proceeding." : "Aborting."
      end
    
      def proceed?
        @answer.y?
      end
    
      def abort?
        @answer.n?
      end
    end
    

    Then use it like so in your task:

    next unless RakeConfirmDialog.new(
      "About to close the Hellmouth forever. Are you sure you want 'Buffy the Vampire Slayer' to have a happy ending?"
    ).confirm!
    

提交回复
热议问题