Class: Outstream::Json

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

Overview

Produce a stream of JSON tokens.

Defined Under Namespace

Classes: Collector, Receiver

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create(&body_block) ⇒ Object

Define an output JSON object, given a block. The block is executed in a context which provides the add method, for adding key-value pairs to the object.

Example:

Outstream::Json.create do
  add string: "hello", number: 42
  add array: [1,2,3]
  add "nested_object" {
    add "foo" => "bar"
  }
end


18
19
20
# File 'lib/outstream/json.rb', line 18

def self.create(&body_block)
  new body_block
end

Instance Method Details

#each(&out_block) ⇒ Object

Iterate the output tokens. The block will receive JSON delimeters individually as strings, and string values as quoted strings. If called without a block, returns an enumerator.

Example:

json.each {|token| puts token} => nil
json.each => an_enumerator


28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/outstream/json.rb', line 28

def each(&out_block)
  e = Enumerator.new {|yielder|
    Collector.new(yielder).collect &@body_block
  }

  if out_block
    e.each(&out_block)
    nil
  else
    e
  end
end

#to_sObject

Produce a compact string of the JSON. The entire string is produced at once; this is not suitable for very large JSON output.



43
44
45
# File 'lib/outstream/json.rb', line 43

def to_s
  "".tap {|s| each {|str| s.concat str } }
end