Sha256: 7a675cafbcbf3b5ddaba0e36b9a438802ae4b920274dc81c20c21dd2d39bdb62

Contents?: true

Size: 1.14 KB

Versions: 3

Compression:

Stored size: 1.14 KB

Contents

module Brief
  class Tree
    def initialize(nodes)
      @nodes = nodes
    end

    def find element_by_id
      elements.detect {|el| el.id == element_by_id }
    end

    def elements
      @elements ||= begin
                      @nodes.map do |node|
                        only      = node.except(:children)

                        visitor = lambda do |child|
                          c_only      = child.except(:children)
                          g_children  = Array(child[:children])

                          g_children.each {|gchild| gchild.parent_id = c_only.id}

                          g_children  = nil if g_children.length == 0

                          [c_only, g_children].compact
                        end

                        children = Array(node[:children]).map(&visitor).flatten
                        children.each {|child| child.parent_id ||= only.id }

                        children = nil if children.length == 0

                        [only, children].compact
                      end

                    end.flatten
    end

    def level level=1
      elements.select {|el| el.level == level }
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
brief-0.0.5 lib/brief/tree.rb
brief-0.0.4 lib/brief/tree.rb
brief-0.0.3 lib/brief/tree.rb