Method: Oj::Doc#each_child

Defined in:
ext/oj/fast.c

#each_child(path = nil) ⇒ Object

Yields to the provided block for each immediate child node with the identified location of the JSON document as the root. The parameter passed to the block on yield is the Doc instance after moving to the child location.

@param [String] path if provided it identified the top of the branch to

process the children of

Examples:

Oj::Doc.open('[3,[2,1]]') { |doc|
    result = []
    doc.each_value('/2') { |doc| result << doc.where? }
    result
}
#=> ["/2/1", "/2/2"]

Yield Parameters:

  • Doc (Doc)

    at the child location

[View source]

1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'ext/oj/fast.c', line 1461

static VALUE doc_each_child(int argc, VALUE *argv, VALUE self) {
    if (rb_block_given_p()) {
        Leaf        save_path[MAX_STACK];
        Doc         doc  = self_doc(self);
        const char *path = 0;
        size_t      wlen;
        Leaf       *where_orig = doc->where;

        wlen = doc->where - doc->where_path;
        if (0 < wlen) {
            memcpy(save_path, doc->where_path, sizeof(Leaf) * (wlen + 1));
        }
        if (1 <= argc) {
            path = StringValuePtr(*argv);
            if ('/' == *path) {
                doc->where = doc->where_path;
                path++;
            }
            if (0 != move_step(doc, path, 1)) {
                if (0 < wlen) {
                    memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
                }
                doc->where = where_orig;
                return Qnil;
            }
        }
        if (NULL == doc->where || NULL == *doc->where) {
            return Qnil;
        }
        if (COL_VAL == (*doc->where)->value_type && 0 != (*doc->where)->elements) {
            Leaf first = (*doc->where)->elements->next;
            Leaf e     = first;

            doc->where++;
            do {
                *doc->where = e;
                rb_yield(self);
                e = e->next;
            } while (e != first);
        }
        if (0 < wlen) {
            memcpy(doc->where_path, save_path, sizeof(Leaf) * (wlen + 1));
        }
        doc->where = where_orig;
    }
    return Qnil;
}