Class: Makiri::DocumentFragment

Inherits:
Node
  • Object
show all
Defined in:
lib/makiri/document_fragment.rb,
ext/makiri/makiri.c

Overview

A detached group of sibling nodes. Build one with DocumentFragment.parse (its own backing document) or Makiri::Document#fragment (bound to an existing document, so its nodes can be spliced in with Node#add_child and friends). Inserting a fragment contributes its children, not the fragment node itself.

The concrete classes are HTML::DocumentFragment and XML::DocumentFragment; their fragment-parsing context differs:

  • HTML is context-sensitive: .parse / Document#fragment accept a Nokogiri-compatible context: keyword naming the element the HTML is parsed inside of - a tag-name String (HTML namespace, e.g. context: "tr"; the bare strings "svg" / "math" name the foreign roots), or a Node element whose tag and namespace are used. The default context is <body>. (Defined in C, ruby_html_*.c.)

  • XML is namespace-context-based (no context: keyword): XML::DocumentFragment.parse is self-contained (a prefix must be declared within the fragment itself), while XML::Document#fragment resolves names against the document’s in-scope namespaces. (C: ruby_xml.c.)

See also Node#parse.

Class Method Summary collapse

Methods inherited from Node

#add_class, #append_class, #at, #attribute, #attribute?, #attributes, #blank?, #cdata?, #classes, #clone, #comment?, #document?, #document_fragment?, #dup, #each, #element?, #inspect, #path, #processing_instruction?, #remove_class, #root, #search, #set_attribute, #text?, #to_h, #traverse

Class Method Details

.parse(*args) ⇒ Object

DocumentFragment.parse(html, context: …) -> standalone fragment with its own backing document (kept alive by the fragment’s wrapper).



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'ext/makiri/glue/ruby_doc.c', line 439

static VALUE
mkr_frag_s_parse(int argc, VALUE *argv, VALUE klass)
{
    (void)klass;
    VALUE html, opts;
    rb_scan_args(argc, argv, "1:", &html, &opts);
    VALUE context = NIL_P(opts) ? Qnil
                                : rb_hash_aref(opts, ID2SYM(rb_intern("context")));

    static const lxb_char_t shell[] = "<html><body></body></html>";
    mkr_parsed_t *parsed = mkr_parse_html(shell, sizeof(shell) - 1, true);
    if (parsed == NULL) {
        rb_raise(mkr_eError, "failed to create fragment document");
    }
    VALUE document = mkr_wrap_document(parsed); /* GC now owns parsed */
    lxb_tag_id_t tag;
    lxb_ns_id_t  ns;
    mkr_resolve_fragment_context(mkr_html_doc_unwrap(document), context, &tag, &ns);
    return mkr_build_fragment_ctx(document, html, tag, ns);
}