Last Updated: September 09, 2019
·
1.319K
· relistan

Two way pipes to external commands in Ruby

Ruby has various standard library methods and classes for implementing pipes to and from external commands (Open3 and spawn for example). These are quite low-level, however, and you end up implementing a lot of logic on your own if you want to do anything complicated.

I recently released a gem called Magritte to make it easy to manage a sub-process with two way pipes. Input is expected to be an IO, while output can be an IO or a Ruby block. A LineBuffer class exists to make handling the output line-by-line easy. Here's some example code:

Magritte::Pipe.from_input_file('some.txt')
  .separated_by("\r\n")
  .line_by_line
  .out_to { |data| puts data }
 .filtering_with('grep "relistan"')

Using Magritte is as easy as adding it to your Gemfile or running gem install magritte.