Class: JsonEmitter::BufferedStream
- Inherits:
-
Object
- Object
- JsonEmitter::BufferedStream
- Includes:
- Enumerable
- Defined in:
- lib/json-emitter/buffered_stream.rb
Overview
Represents a stream of JSON to be generated and yielded. It can be treated like any Enumerable. Unlike JsonEmitter::Stream, the yielded output is buffered into (roughly) equally sized chunks.
Instance Method Summary collapse
-
#each ⇒ Enumerator
If a block is given, each chunk of JSON is yielded to it.
-
#initialize(enum, buffer_size, unit: :kb) ⇒ BufferedStream
constructor
Initialize a new buffered stream.
-
#unbuffered ⇒ JsonEmitter::Stream
Returns an unbuffered version of the stream.
-
#write(io) ⇒ Object
Write the stream to the specified IO object.
Constructor Details
#initialize(enum, buffer_size, unit: :kb) ⇒ BufferedStream
Initialize a new buffered stream.
16 17 18 19 20 21 22 23 24 |
# File 'lib/json-emitter/buffered_stream.rb', line 16 def initialize(enum, buffer_size, unit: :kb) @enum = enum @buffer_size = case unit when :bytes then buffer_size when :kb then buffer_size * 1024 when :mb then buffer_size * 1024 * 1024 else raise ArgumentError, "unknown buffer size unit ':#{unit}'" end end |
Instance Method Details
#each ⇒ Enumerator
If a block is given, each chunk of JSON is yielded to it. If not block is given, an Enumerator is returned.
51 52 53 54 55 56 57 58 59 |
# File 'lib/json-emitter/buffered_stream.rb', line 51 def each if block_given? buffer.each { |str| yield str } else buffer end end |
#unbuffered ⇒ JsonEmitter::Stream
Returns an unbuffered version of the stream.
31 32 33 |
# File 'lib/json-emitter/buffered_stream.rb', line 31 def unbuffered Stream.new(@enum) end |
#write(io) ⇒ Object
Write the stream to the specified IO object.
40 41 42 43 44 |
# File 'lib/json-emitter/buffered_stream.rb', line 40 def write(io) buffer.each { |str| io << str } end |