Ruby IOError on a closed stream
Reading through a closed Ruby stream can raise IOError. The receipt preview must start with a reader that is still open.
A simple example
IOError on a closed stream
- Start with A reader has already been closed
- Do this Try another read
- Result Read fails
Syntax
reader.readline
Run these examples in Ruby
Save one example at a time as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rbRead from a finished receipt import
A receipt importer closes its reader at the end of a batch. If the preview screen asks for another line through that reader, the application needs to detect the stale handle and open a new reader for the next batch.
require "stringio"
reader = StringIO.new("Receipt 42")
reader.close
begin
puts reader.readline
rescue IOError
puts "Open a new reader"
end
Open a new reader
The importer closed this reader before the preview tried to read. A fresh reader is needed for another pass.
Read the first rehearsal note
The music desk has just opened a reader containing a short note. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.
Revisit a completed import
A receipt reader was closed before the operator requested the next character. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.
What to watch for
EOFError is also an IOError. Handle it separately if an empty but open input has its own meaning.