Class: Xing::Services::JsonTreeLister

Inherits:
Object
  • Object
show all
Defined in:
lib/xing/services/json_tree_lister.rb

Defined Under Namespace

Classes: TreeNode

Instance Method Summary collapse

Constructor Details

#initialize(nodes, node_serializer) ⇒ JsonTreeLister

Returns a new instance of JsonTreeLister.



19
20
21
22
23
24
# File 'lib/xing/services/json_tree_lister.rb', line 19

def initialize(nodes, node_serializer)
  @nodes = nodes
  @node_serializer = node_serializer
  @stack = [[]]
  @path = []
end

Instance Method Details

#pop_levelObject



30
31
32
33
# File 'lib/xing/services/json_tree_lister.rb', line 30

def pop_level
  children = @stack.pop
  @stack.last << render_node(@path.pop, children)
end

#renderObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/xing/services/json_tree_lister.rb', line 35

def render
  (@nodes + [nil]).each_cons(2) do |this, after|
    until @path.empty? or @path.last.is_ancestor_of?(this)
      pop_level
    end
    if after.nil? or !this.is_ancestor_of?(after)
      @stack.last << render_node(this, [])
    else
      @path << this
      @stack << []
    end
  end
  until @path.empty?
    pop_level
  end
  return @stack.last.first
end

#render_node(node, children) ⇒ Object



26
27
28
# File 'lib/xing/services/json_tree_lister.rb', line 26

def render_node(node, children)
  @node_serializer.new(TreeNode.new(node, children)).as_json
end