Class | Yajl::Encoder |
In: |
lib/yajl.rb
ext/yajl_ext.c |
Parent: | Object |
A helper method for encode-and-forget use-cases
Examples:
Yajl::Encoder.encode(obj[, io, :pretty => true, :indent => "\t", &block]) output = Yajl::Encoder.encode(obj[, :pretty => true, :indent => "\t", &block])
obj is a ruby object to encode to JSON format
io is the optional IO stream to encode the ruby object to. If io isn‘t passed, the resulting JSON string is returned. If io is passed, nil is returned.
The options hash allows you to set two encoding options - :pretty and :indent
:pretty accepts a boolean and will enable/disable "pretty printing" the resulting output
:indent accepts a string and will be used as the indent character(s) during the pretty print process
If a block is passed, it will be used as (and work the same as) the on_progress callback
obj is the Ruby object to encode to JSON
io is an optional IO used to stream the encoded JSON string to. If io isn‘t specified, this method will return the resulting JSON string. If io is specified, this method returns nil
If an optional block is passed, it‘s called when encoding is complete and passed the resulting JSON string
It should be noted that you can reuse an instance of this class to continue encoding multiple JSON to the same stream. Just continue calling this method, passing it the same IO object with new/different ruby objects to encode. This is how streaming is accomplished.
Document-method: on_progress
This callback setter allows you to pass a Proc/lambda or any other object that responds to call.
It will pass the caller a chunk of the encode buffer after it‘s reached it‘s internal max buffer size (defaults to 8kb). For example, encoding a large object that would normally result in 24288 bytes of data will result in 3 calls to this callback (assuming the 8kb default encode buffer).