Sha256: 87e6b7534391600df561ff3272c7ac895f9706f7dd96b0aff967b97b6d312210
Contents?: true
Size: 1.74 KB
Versions: 2
Compression:
Stored size: 1.74 KB
Contents
# encoding: UTF-8 class JsonWriteStream class YieldingWriter attr_reader :stream, :index def initialize(stream) @stream = stream @index = 0 after_initialize end def after_initialize end def write_object(comma_written = false) unless comma_written write_comma increment end yield writer = YieldingObjectWriter.new(stream) writer.close end def write_array(comma_written = false) unless comma_written write_comma increment end yield writer = YieldingArrayWriter.new(stream) writer.close end def close stream.close end protected def escape(str) JSON.generate([str])[1..-2] end def write_comma stream.write(',') if index > 0 end def increment @index += 1 end end class YieldingObjectWriter < YieldingWriter def after_initialize stream.write('{') end def write_array(key) write_comma increment write_key(key) stream.write(':') super(true) end def write_object(key) write_comma increment write_key(key) stream.write(':') super(true) end def write_key_value(key, value) write_comma increment write_key(key) stream.write(":#{escape(value)}") end def close stream.write('}') end private def write_key(key) stream.write(escape(key.to_s)) end end class YieldingArrayWriter < YieldingWriter def after_initialize stream.write('[') end def write_element(element) write_comma increment stream.write(escape(element)) end def close stream.write(']') end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
json-write-stream-1.0.1 | lib/json-write-stream/yielding.rb |
json-write-stream-1.0.0 | lib/json-write-stream/yielding.rb |