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 Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rack_env: nil) ⇒ Emitter

Returns a new instance of Emitter.



11
12
13
# File 'lib/json-emitter/emitter.rb', line 11

def initialize(rack_env: nil)
  @context = Context.new(rack_env: rack_env)
end

Instance Attribute Details

#contextJsonEmitter::Context (readonly)



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

def context
  @context
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)


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

def array(enum, &mapper)
  Enumerator.new { |y|
    context.execute {
      array_generator(enum, &mapper).each { |json_val|
        y << json_val
      }
    }
  }
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)


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

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