class Outstream::Json

Produce a stream of JSON tokens.

Public Class Methods

create(&body_block) click to toggle source

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
# File lib/outstream/json.rb, line 18
def self.create(&body_block)
  new body_block
end
new(body_block) click to toggle source
# File lib/outstream/json.rb, line 49
def initialize(body_block)
  @body_block = body_block
end

Public Instance Methods

each(&out_block) click to toggle source

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
# 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_s() click to toggle source

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

# File lib/outstream/json.rb, line 43
def to_s
  "".tap {|s| each {|str| s.concat str } }
end