Say you're trying to consume a streaming API using Faraday. And say you need to consume the content line-by-line.
Let's explore one way of doing that.
- Faraday allows setting
.options.on_data
on the request to aProc
to run as data is streamed. - We maintain a buffer for the current line we're reading.
- As we receive content, we scan through it looking for newlines.
- Every time we find a newline, we append what we've scanned to the buffer and flush it (yield it as a
String
). - If we encounter the end of a chunk, we append what's left to the buffer.
- When we've finished streaming content, we check if we were in the middle of an incomplete line, and if so flush the buffer one last time.
To run the demo
- Make sure you have the following installed
- Ruby (obviously)
faraday
(for the client)sinatra
(for the server)
- Run
ruby server.rb
in one terminal - Run
ruby client.rb
in another terminal - Witness the streaming output