Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test filter-like Ruby scripts with Pry?

I have a simple script which process the lines coming from STDIN. Sometimes an exception arise - some UTF-8 conversion error - and I would like to examine the variables, what cause the error. I use the following syntax in my file (let's call filter.rb), but I never get a Pry prompt:

#!/usr/bin/ruby
require "pry"

n=0
while line=STDIN.gets do
 begin
   n=n+1
   raise "an exception" if n==2
 rescue => e
   binding.pry
 end
end

When I issue:

cat data.txt|ruby filter.rb

I see on the screen:

     5:   while line= STDIN.gets do
     6:    begin
     7:      n=n+1
     8:      raise "an exception" if n==2
     9:    rescue => e
 => 10:      binding.pry
    11:    end
    12:   end

But in fact all I get is a bash prompt, not a Pry command prompt.

like image 371
Konstantin Avatar asked Sep 12 '25 22:09

Konstantin


1 Answers

The problem is that Pry uses Readline, which in turn reads from stdin. If you use ruby as a filter, stdin no longer is a terminal (isatty will be false). So Readline won't be able to use stdin and silently marches on (or gives a syntax error and marches on, if you're lucky).

You can give Readline a working tty by adding

require "readline"
Readline.input = IO.new(IO.sysopen("/dev/tty", "r+"))

to your code.

The Pry documentation hints at this solution, but I do not know if this is sanctioned by Pry, or if it could cause weird interactions with other parts of Pry, Ruby and whatever other moving bits you may have in your app... YMMV.

like image 53
BertD Avatar answered Sep 14 '25 16:09

BertD