Ruby non-blocking string

I am trying to read a line from io in a non-blocking way.

Unfortunately readline blocks. I think I can solve this with read_nonblock with an additional buffer, where I store a partial result, check if there are several lines in the buffer, etc., but this seems a bit complicated for a simple task like this. Is there a better way to do this?

Note: I use event demultiplexing ( select ), and I am very pleased with it, I do not want to create threads, use EventMachine, etc.

+7
source share
2 answers

I think the read_nonblock solution is probably the way to go. A simple, not as effective version of the monkey patch:

 class IO def readline_nonblock rlnb_buffer = "" while ch = self.read_nonblock(1) rlnb_buffer << ch if ch == "\n" then result = rlnb_buffer return result end end end end 

This throws an exception if there is no ready data, like read_nonblock, so you need to save this to just get zero, etc.

+5
source

This implementation improves Mark Reed's answer by not discarding a data reading that does not end on a new line:

 class IO def readline_nonblock buffer = "" buffer << read_nonblock(1) while buffer[-1] != "\n" buffer rescue IO::WaitReadable => blocking raise blocking if buffer.empty? buffer end end 
+3
source

All Articles