module Treeify

Public Instance Methods

ancestors() click to toggle source
# File lib/treeify.rb, line 98
def ancestors
  self.class.tree_for_ancestors(self)
end
build_tree(data) click to toggle source
# File lib/treeify.rb, line 119
def build_tree(data)
  # turn our AoH into a hash where we've mapped the ID column
  # to the rest of the hash + a comments array for nested comments
  nested_hash = Hash[data.map{|e| [e['id'], e.merge('children' => [])]}]

  # if we have a parent ID, grab all the comments
  # associated with that parent and push them into the comments array
  nested_hash.each do |id, item|
    parent = nested_hash[item['parent_id']]
    parent['children'] << item if parent
  end

  # return the values of our nested hash, ie our actual comment hash data
  # reject any descendents whose parent ID already exists in the main hash so we don't
  # get orphaned descendents listed as their own comment
   
  nested_hash.reject{|id, item| 
    nested_hash.has_key? item['parent_id']
  }.values
end
descendent_tree() click to toggle source
# File lib/treeify.rb, line 114
def descendent_tree
  # give build_tree an array of hashes with the AR objects serialized into a hash
  build_tree(descendents.to_a.map(&:serializable_hash))
end
descendents() click to toggle source
# File lib/treeify.rb, line 94
def descendents
  self_and_descendents - [self]
end
is_root?() click to toggle source
# File lib/treeify.rb, line 106
def is_root?
  self.parent_id != nil
end
self_and_descendents() click to toggle source
# File lib/treeify.rb, line 102
def self_and_descendents
  self.class.tree_for(self)
end
siblings() click to toggle source
# File lib/treeify.rb, line 110
def siblings
  self.class.where(parent_id: self.parent_id) - [self]
end