在 rake 任务中接受来自控制台/命令提示符的用户输入 [英] Accepting user input from the console/command prompt inside a rake task

查看:34
本文介绍了在 rake 任务中接受来自控制台/命令提示符的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Rails 编写一个自定义的 rake 任务,程序有一个地方总结了它要做什么,然后询问用户它要做什么是正确的.

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.

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

然而,这段代码会导致rake过早中止;

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

rake aborted!
No such file or directory - populate

"populate" 是 rake 任务的名称.

"populate" is the name of the rake task.

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

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

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

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.

但是,我不知道如何解决此错误.rake 是否提供了 .gets 的替代方法?

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

推荐答案

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

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.

接受输入是用 STDIN.gets.chomp 而不是 gets.chomp 完成的.

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

您可以使用以下命令运行此 rake 任务:rake db:populate

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

这篇关于在 rake 任务中接受来自控制台/命令提示符的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆