1

So I'm trying to DRY up a Rake task which runs a script that takes user input, and I've run into the same problem as this poster - by default, just calling gets assumes that the rake argument (in this case, db:seed) is a file from which it should read, which of course doesn't exist. I got around this by just calling STDIN.gets, which works fine, but I'd love to be able to just use gets the way I can use puts (Rake seems to have no issue with STDOUT by default) - as a static method.

Is there any way to force Kernel#gets to read from STDIN within Rake? (Or more generally, is there any way to force Kernel#gets to read from STDIN when it is ostensibly passed a command line argument?) Or would that be a bad practice?

Community
  • 1
  • 1
wisew
  • 2,672
  • 3
  • 23
  • 30
  • 1
    This is actually general Ruby behavior, not specific to rake; i.e. any script with bare `gets` will try to read from a file named by a command-line option. – echristopherson Jun 18 '13 at 21:38
  • 3
    There are ways, but why? `STDIN.gets` is a perfectly elegant solution and how it should be done. The other ways involve code adjusting `$stdin` which might break something else immediately, or paint you into a corner. – the Tin Man Jun 18 '13 at 21:44

1 Answers1

0

(Answered by @the-tin-man in this comment)

There's really very little advantage to be gained in DRYness from forcing Kernel#gets to read from STDIN in any context, including Rake. Although it can be done (by modifying $stdin), it shouldn't be done because it would just be brittle and hacky.

Community
  • 1
  • 1
wisew
  • 2,672
  • 3
  • 23
  • 30