Method: Yajl::Encoder#encode

Defined in:
ext/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.



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'ext/yajl_ext.c', line 530

static VALUE rb_yajl_encoder_encode(int argc, VALUE * argv, VALUE self) {
    struct 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);
    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;
}