Class: JsonEmitter::Emitter

Inherits:
Object
  • Object
show all
Defined in:
lib/json-emitter/emitter.rb

Overview

Builds Enumerators that yield JSON from Ruby Arrays or Hashes.

Instance Method Summary collapse

Constructor Details

#initializeEmitter

Returns a new instance of Emitter.



6
7
8
9
10
11
# File 'lib/json-emitter/emitter.rb', line 6

def initialize
  @wrappers = JsonEmitter.wrappers.map(&:call).compact
  @error_handlers = JsonEmitter.error_handlers
  @pass_through_errors = []
  @pass_through_errors << Puma::ConnectionError if defined? Puma::ConnectionError
end

Instance Method Details

#array(enum) { ... } ⇒ Enumerator

Generates an Enumerator that will stream out a JSON array.

Parameters:

  • enum (Enumerable)

    Something that can be enumerated over, like an Array or Enumerator. Each element should be something that can be rendered as JSON (e.g. a number, string, boolean, Array, or Hash).

Yields:

  • If a block is given, it will be yielded each value in the array. The return value from the block will be converted to JSON instead of the original value.

Returns:

  • (Enumerator)


20
21
22
23
24
25
26
27
28
# File 'lib/json-emitter/emitter.rb', line 20

def array(enum, &mapper)
  Enumerator.new { |y|
    wrapped {
      array_generator(enum, &mapper).each { |json_val|
        y << json_val
      }
    }
  }
end

#error(&handler) ⇒ Object

Add an error handler. TODO better docs and examples.



56
57
58
# File 'lib/json-emitter/emitter.rb', line 56

def error(&handler)
  @error_handlers += [handler]
end

#object(hash) ⇒ Enumerator

Generates an Enumerator that will stream out a JSON object.

Parameters:

  • hash (Hash)

    Keys should be Strings or Symbols and values should be any JSON-compatible value like a number, string, boolean, Array, or Hash.

Returns:

  • (Enumerator)


36
37
38
39
40
41
42
43
44
# File 'lib/json-emitter/emitter.rb', line 36

def object(hash)
  Enumerator.new { |y|
    wrapped {
      object_generator(hash).each { |json_val|
        y << json_val
      }
    }
  }
end

#wrap(&block) ⇒ Object

Wrap the enumeration in a block. It will be passed a callback which it must call to continue. TODO better docs and examples.



48
49
50
51
52
# File 'lib/json-emitter/emitter.rb', line 48

def wrap(&block)
  if (wrapper = block.call)
    @wrappers.unshift wrapper
  end
end