Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

rake aborted!
No such file or directory - populate

"populate" is the name of the rake task.

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

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.

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

like image 977
Starkers Avatar asked Sep 30 '13 06:09

Starkers


People also ask

How do you call a rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.

What is rake task in rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.


1 Answers

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

like image 71
Rajarshi Das Avatar answered Sep 20 '22 12:09

Rajarshi Das