class Outstream::Json::Collector

Public Class Methods

new(yielder) click to toggle source
# File lib/outstream/json.rb, line 63
def initialize(yielder)
  @yielder = yielder
  @count = [0]
end

Public Instance Methods

add(objs, &block) click to toggle source
# File lib/outstream/json.rb, line 81
def add(objs, &block)
  if block
    add_key objs
    add_object &block
  else
    add_to_object objs
  end
end
add_array(a) click to toggle source
# File lib/outstream/json.rb, line 113
def add_array(a)
  begin
    write "["
    a.enum_for(:each).each_with_index {|v,i|
      write "," if i > 0
      add_value v
    }
  rescue
    raise
  ensure
    write "]"
  end
end
add_key(key) click to toggle source
# File lib/outstream/json.rb, line 95
def add_key(key)
  write "," if @count.last > 0
  write key.to_json
  write ":"
  @count[@count.size-1] += 1
end
add_object() { || ... } click to toggle source
# File lib/outstream/json.rb, line 101
def add_object
  begin
    write "{"
    @count.push 0
    return yield
  rescue
    raise
  ensure
    @count.pop
    write "}"
  end
end
add_to_object(objs) click to toggle source
# File lib/outstream/json.rb, line 89
def add_to_object(objs)
  objs.each_pair {|key,val|
    add_key key
    add_value val
  }
end
add_value(value) click to toggle source
# File lib/outstream/json.rb, line 126
def add_value(value)
  if value.respond_to?:each_pair
    add_object { add_to_object value }
  elsif value.respond_to?:each
    add_array value
  elsif value.respond_to?:call
    begin
      add_value value.call
    rescue
      add_value nil
      raise
    end
  else
    write value.to_json
  end
end
collect(&block) click to toggle source
# File lib/outstream/json.rb, line 67
def collect(&block)
  add_object {
    receiver = Receiver.new self
    if block.arity == 1
      block[receiver]
    else
      (class << receiver; self; end).send(:define_method, :__call_block, &block)
      receiver.__call_block
    end
  }
end
write(str) click to toggle source
# File lib/outstream/json.rb, line 78
def write(str)
  @yielder << str
end