Last Updated: February 25, 2016
·
4.597K
· jsmestad

Getting input from inside a Rake task

TL;DR

Use STDIN.gets instead of just gets. Rake does not make STDIN implicitly available.

Long Version

I was writing a quick Rake task this morning and needed to convert a pretty basic script that takes user input and passes it to a ActiveRecord finder, but the script that worked via rails runner failed with this error when moving it inside a Rake task.

Original Script:

def prompt(*args)
  print(*args)
  gets
end

username = prompt "What is the username of the user you wishing to configure? "
password = prompt "What is this user's password? "
u = User.where(username: username).first

if u.activate_user!(password)
  puts "Successfully activated user #{username}"
else
  puts "Failed to activate user #{username}. Was your password wrong?"
end

Moving it into a Rake task. The cryptic error I received was

What is the username of the user you wishing to configure?rake aborted!
No such file or directory @ rb_sysopen - my_app:configure_user`

The issue is that Rake does not make STDIN implicitly available. A simple change was to the prompt method:

def prompt(*args)
  print(*args)
  STDIN.gets
end