从rake任务中的控制台/命令提示符接受用户输入

时间:2021-10-29 02:17:49

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 correct.

我正在为Rails编写一个自定义rake任务,程序在这个点上总结它将要做什么,然后问用户它将要做什么是正确的。

puts "\n Is this what you want to happen? [Y/N]"
answer = gets.chomp

if answer == "Y"
    # commits
else if answer == "N"
    return false #(Aborts the rake task)
end

However, this code causes the rake to be aborted prematurely;

但是,该代码导致rake提前终止;

rake aborted!
No such file or directory - populate

"populate" is the name of the rake task.

“填充”是rake任务的名称。

I think what's really causing this error in the .gets method.

我认为是什么导致了。gets方法中的错误。

I don't know how the .gets method explicitly works, but I'm guessing it must automatically send the user input back to the file where the script is written, and for some reason it's getting confused and it thinks the name of the rake task is the name of the file. As populate.rake doesn't exist, I think this is why the error is being thrown.

我不知道.gets方法是如何明确地工作的,但是我猜它必须自动地将用户输入发送回编写脚本的文件中,出于某种原因,它会感到困惑,并认为rake任务的名称是文件的名称。填充。rake不存在,我认为这就是抛出错误的原因。

However, I don't know how I can get around this error. Does rake offer an alternate method to .gets?

然而,我不知道怎样才能避免这个错误。rake提供了另一种方法到。get吗?

1 个解决方案

#1


21  

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.

Rake任务存储在Rails应用程序的lib/tasks文件夹中。rake任务的文件应该以.rake扩展名结束;例如:populate.rake。

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

接受输入是用stdin .get完成的。chomp代替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

您可以使用:rake db:populate来运行这个任务

#1


21  

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.

Rake任务存储在Rails应用程序的lib/tasks文件夹中。rake任务的文件应该以.rake扩展名结束;例如:populate.rake。

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

接受输入是用stdin .get完成的。chomp代替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

您可以使用:rake db:populate来运行这个任务