Method: Oj::StreamWriter.new

Defined in:
ext/oj/stream_writer.c

.new(io, options) ⇒ Object

Creates a new StreamWriter. Options are supported according the specified mode or the mode in the default options. Note that if mimic_JSON or Oj.optimize_rails has not been called then the behavior of the modes may not be the same as if they were.

In addition to the regular dump options for the various modes a :buffer_size option is available. It should be set to a positive integer. It is considered a hint of how large the initial internal buffer should be and also a hint on when to flush.

  • io [IO] stream to write to

  • options [Hash] formatting options



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'ext/oj/stream_writer.c', line 74

static VALUE stream_writer_new(int argc, VALUE *argv, VALUE self) {
    StreamWriterType type   = STREAM_IO;
    int              fd     = 0;
    VALUE            stream = argv[0];
    VALUE            clas   = rb_obj_class(stream);
    StreamWriter     sw;
#if !IS_WINDOWS
    VALUE s;
#endif

    if (oj_stringio_class == clas) {
        type = STRING_IO;
#if !IS_WINDOWS
    } else if (rb_respond_to(stream, oj_fileno_id) && Qnil != (s = rb_funcall(stream, oj_fileno_id, 0)) &&
               0 != (fd = FIX2INT(s))) {
        type = FILE_IO;
#endif
    } else if (rb_respond_to(stream, oj_write_id)) {
        type = STREAM_IO;
    } else {
        rb_raise(rb_eArgError, "expected an IO Object.");
    }
    sw = OJ_R_ALLOC(struct _streamWriter);
    if (2 == argc && T_HASH == rb_type(argv[1])) {
        volatile VALUE v;
        int            buf_size = 0;

        if (Qundef == buffer_size_sym) {
            buffer_size_sym = ID2SYM(rb_intern("buffer_size"));
            rb_gc_register_address(&buffer_size_sym);
        }
        if (Qnil != (v = rb_hash_lookup(argv[1], buffer_size_sym))) {
            if (rb_cInteger != rb_obj_class(v)) {
                OJ_R_FREE(sw);
                rb_raise(rb_eArgError, ":buffer size must be a Integer.");
            }
            buf_size = FIX2INT(v);
        }
        oj_str_writer_init(&sw->sw, buf_size);
        oj_parse_options(argv[1], &sw->sw.opts);
        sw->flush_limit = buf_size;
    } else {
        oj_str_writer_init(&sw->sw, 4096);
        sw->flush_limit = 0;
    }
    sw->sw.out.indent = sw->sw.opts.indent;
    sw->stream        = stream;
    sw->type          = type;
    sw->fd            = fd;

    return TypedData_Wrap_Struct(oj_stream_writer_class, &oj_stream_writer_type, sw);
}