Method: Yajl::Encoder#encode
- Defined in:
- ext/yajl/yajl_ext.c
#encode(*args) ⇒ Object
call-seq: encode(obj[, io[, &block]])
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.
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
# File 'ext/yajl/yajl_ext.c', line 1100
static VALUE rb_yajl_encoder_encode(int argc, VALUE * argv, VALUE self) {
yajl_encoder_wrapper * wrapper;
const unsigned char * buffer;
unsigned int len;
VALUE obj, io, blk, outBuff;
GetEncoder(self, wrapper);
rb_scan_args(argc, argv, "11&", &obj, &io, &blk);
if (blk != Qnil) {
wrapper->on_progress_callback = blk;
}
/* begin encode process */
yajl_encode_part(wrapper, obj, io);
/* just make sure we output the remaining buffer */
yajl_gen_get_buf(wrapper->encoder, &buffer, &len);
outBuff = rb_str_new((const char *)buffer, len);
#ifdef HAVE_RUBY_ENCODING_H
rb_enc_associate(outBuff, utf8Encoding);
#endif
yajl_gen_clear(wrapper->encoder);
if (io != Qnil) {
rb_io_write(io, outBuff);
if (wrapper->terminator != 0 && wrapper->terminator != Qnil) {
rb_io_write(io, wrapper->terminator);
}
return Qnil;
} else if (blk != Qnil) {
rb_funcall(blk, intern_call, 1, outBuff);
if (wrapper->terminator != 0) {
rb_funcall(blk, intern_call, 1, wrapper->terminator);
}
return Qnil;
} else {
if (wrapper->terminator != 0 && wrapper->terminator != Qnil) {
rb_str_concat(outBuff, wrapper->terminator);
}
return outBuff;
}
return Qnil;
}
|