class Sirens::VirtualTreeModel

Public Class Methods

new(roots: [], get_children_block:) click to toggle source

Initializing

Calls superclass method
# File lib/models/virtual_tree_model.rb, line 23
def initialize(roots: [], get_children_block:)
    super()

    @get_children_block = get_children_block

    @roots = roots.collect{ |item| new_tree_node_on(item) }
end
on(root_items) click to toggle source
# File lib/models/virtual_tree_model.rb, line 16
def on(root_items)
    self.new(root_items)
end
with(root_item) click to toggle source
# File lib/models/virtual_tree_model.rb, line 8
def with(root_item)
    self.on([root_item])
end
with_all(root_items) click to toggle source
# File lib/models/virtual_tree_model.rb, line 12
def with_all(root_items)
    self.on(root_items.clone)
end

Public Instance Methods

children_at(path:) click to toggle source
# File lib/models/virtual_tree_model.rb, line 67
def children_at(path:)
    node_at(path: path).children.collect{ |node| node.value }
end
item_at(path:) click to toggle source
# File lib/models/virtual_tree_model.rb, line 63
def item_at(path:)
    node_at(path: path).value
end
new_tree_node_on(item) click to toggle source
# File lib/models/virtual_tree_model.rb, line 31
def new_tree_node_on(item)
    TreeNode.new(value: item, get_children_block: @get_children_block)
end
node_at(path:) click to toggle source
# File lib/models/virtual_tree_model.rb, line 53
def node_at(path:)
    node = @roots[path.first]

    path[1..-1].each do |child_index|
        node = node.child_at(index: child_index)
    end

    node
end
objects_hierarchy_at(path:) click to toggle source

Given a path returns an array with the objects on each tree level corresponding to each index in the path.

# File lib/models/virtual_tree_model.rb, line 91
def objects_hierarchy_at(path:)
    return [] if path.nil?

    nodes = @roots

    path.inject([]) { |hierarchy, index|
        node = nodes[index]

        hierarchy << node.value

        nodes = node.children

        hierarchy
    }
end
path_of(objects_hierarchy) click to toggle source

Given a hierarchy of objects in the tree, returns an array with the path indices.

# File lib/models/virtual_tree_model.rb, line 74
def path_of(objects_hierarchy)
    objects = @roots

    objects_hierarchy.inject([]) { |path, each_object|
        index = objects.index { |node| node.value == each_object }

        path << index

        objects = objects[index].children

        path
    }
end
roots() click to toggle source

Accessing

# File lib/models/virtual_tree_model.rb, line 37
def roots()
    @roots.collect{ |node| node.value }
end
set_roots(new_roots) click to toggle source
# File lib/models/virtual_tree_model.rb, line 41
def set_roots(new_roots)
    old_roots = roots

    @roots = new_roots.collect{ |item| new_tree_node_on(item) }

    changed

    notify_observers(
        TreeChanged.new(new_roots: new_roots, old_roots: old_roots)
    )
end