Accepting user input from the console/command prompt inside a rake task

后端 未结 1 1717
暗喜
暗喜 2021-02-19 05:30

I\'m writing a custom rake task for Rails, and there is a point the program where it summarises what it\'s going to do and then asks the user if what it\'s about to do is correc

1条回答
  •  耶瑟儿~
    2021-02-19 06:01

    Rake tasks are stored in the lib/tasks folder of the Rails application. The rake task's file should end with the .rake extension; for example: populate.rake.

    Accepting the input is done with STDIN.gets.chomp instead of gets.chomp.

    namespace :db do
      desc "Prints the migrated versions"
      task :populate => :environment do
        puts "\n Is this what you want to happen? [Y/N]"
        answer = STDIN.gets.chomp
        puts answer
        if answer == "Y"
          # your code here
        elsif answer == "N"
          return false # Abort the rake task
        end
      end
    end
    

    You can run this rake task with: rake db:populate

    0 讨论(0)
提交回复
热议问题