Module: Treeify
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/treeify.rb
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
- #ancestors ⇒ Object
- #build_tree(data) ⇒ Object
- #descendent_tree ⇒ Object
- #descendents ⇒ Object
- #is_root? ⇒ Boolean
- #self_and_descendents ⇒ Object
- #siblings ⇒ Object
Instance Method Details
#ancestors ⇒ Object
73 74 75 |
# File 'lib/treeify.rb', line 73 def ancestors self.class.tree_for_ancestors(self) end |
#build_tree(data) ⇒ Object
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/treeify.rb', line 94 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 ⇒ Object
89 90 91 92 |
# File 'lib/treeify.rb', line 89 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 ⇒ Object
69 70 71 |
# File 'lib/treeify.rb', line 69 def descendents self_and_descendents - [self] end |
#is_root? ⇒ Boolean
81 82 83 |
# File 'lib/treeify.rb', line 81 def is_root? self.parent_id != nil end |
#self_and_descendents ⇒ Object
77 78 79 |
# File 'lib/treeify.rb', line 77 def self_and_descendents self.class.tree_for(self) end |
#siblings ⇒ Object
85 86 87 |
# File 'lib/treeify.rb', line 85 def siblings self.class.where(parent_id: self.parent_id) - [self] end |