class Trivet::Document

A Trivet::Document object holds the root of a tree. It is not necessary to have a Trivet::Document object to create a tree, but it can be handy to have an object that holds the tree but is not part of the tree itself.

Attributes

misc[R]

A hash of any miscellaneous information you want to attach to the node.

root[R]

Returns the root node. Returns nil if the document does not have a root.

Public Class Methods

new(new_root=nil) click to toggle source

Accepts an optional root node.

# File lib/trivet.rb, line 1438
def initialize(new_root=nil)
        # init
        @root = nil
        @misc = {}
        
        # set new root
        if new_root
                if new_root.is_a?(Class)
                        new_root = new_root.new()
                end
                
                new_root.parent = self
        end
end

Public Instance Methods

[](id) click to toggle source

Shortcut for node_by_id().

# File lib/trivet.rb, line 1579
def [](id)
        return node_by_id(id)
end
children() click to toggle source

If there is a root node, returns an array consisting of just the root node. Else returns an empty array. This method if is a convenience to that a node can always call its parent's children.

# File lib/trivet.rb, line 1525
def children
        if @root
                return [@root]
        else
                return []
        end
end
query(qobj, opts={}, &block) click to toggle source

Runs a query starting with, and including, the root node. See Trivet::Node#query for details.

# File lib/trivet.rb, line 1564
def query(qobj, opts={}, &block)
        opts = {'self'=>true}.merge(opts)
        return @root.query(qobj, opts, &block)
end
root=(new_root) click to toggle source

Sets a new root for the tree. This method is a shortcut for set_root().

# File lib/trivet.rb, line 1477
def root=(new_root)
        set_root new_root
end
set_root(new_root, opts={}) click to toggle source

Sets the root node. The given object must be a Trivet::Node object or nil.

# File lib/trivet.rb, line 1491
def set_root(new_root, opts={})
        # $tm.hrm
        opts = {'recurse'=>true}.merge(opts)
        
        # must be node
        unless new_root.is_a?(Trivet::Node) or new_root.nil?
                raise 'root-not-trivet-node-or-nil'
        end
        
        # unlink old root
        if @root and opts['recurse']
                @root.unlink('recurse'=>false)
        end
        
        # set root
        @root = new_root
        
        # set parent
        if new_root and opts['recurse']
                new_root.parent = self
        end
end
traverse(&block) click to toggle source

Traverses the tree starting with the root node. See Trivet::Node#traverse for details.

# File lib/trivet.rb, line 1544
def traverse(&block)
        # if no root
        if not @root
                raise 'cannot-traverse-without-root'
        end
        
        # traverse
        @root.traverse 'self'=>true, &block
end