Class: JsonEmitter::BufferedStream

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(enum, buffer_size, unit: :kb) ⇒ BufferedStream

Initialize a new buffered stream.

Parameters:

  • enum (Enumerator)

    An enumerator that yields pieces of JSON.

  • buffer_size (Integer)

    The buffer size in kb. This is a size hint, not a hard limit.

  • unit (Symbol) (defaults to: :kb)

    :bytes | :kb (default) | :mb



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

#eachEnumerator

If a block is given, each chunk of JSON is yielded to it. If not block is given, an Enumerator is returned.

Returns:

  • (Enumerator)


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

#unbufferedJsonEmitter::Stream

Returns an unbuffered version of the stream.

Returns:



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.

Parameters:

  • io (IO)


40
41
42
43
44
# File 'lib/json-emitter/buffered_stream.rb', line 40

def write(io)
  buffer.each { |str|
    io << str
  }
end