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
98 99 100 |
# File 'lib/treeify.rb', line 98 def ancestors self.class.tree_for_ancestors(self) end |
#build_tree(data) ⇒ Object
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
# 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 ⇒ Object
114 115 116 117 |
# 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 ⇒ Object
94 95 96 |
# File 'lib/treeify.rb', line 94 def descendents self_and_descendents - [self] end |
#is_root? ⇒ Boolean
106 107 108 |
# File 'lib/treeify.rb', line 106 def is_root? self.parent_id != nil end |
#self_and_descendents ⇒ Object
102 103 104 |
# File 'lib/treeify.rb', line 102 def self_and_descendents self.class.tree_for(self) end |
#siblings ⇒ Object
110 111 112 |
# File 'lib/treeify.rb', line 110 def siblings self.class.where(parent_id: self.parent_id) - [self] end |