acts_as_tree icon indicating copy to clipboard operation
acts_as_tree copied to clipboard

Usefull methods?

Open RichardK opened this issue 15 years ago • 1 comments

Hi. What about adding some usefull methods to your plug in: leafs: returns only the last elements of a tree for a given knot structure: returns the given knot and all elements under the knot

Hereby a suggestion of code - it works pretty nice:

module ActiveRecord module Acts module Tree module ClassMethods def structure(knot=find(0)) #Returns an array of knot and all elements under knot y = Array.new y[0] = knot if y[0].children.first then looping(y, knot) end return y end def leafs(knot=find(0)) #Returns only the last elements of your tree under the tree object knot @@tmp = structure(knot) @leafs = Array.new @@tmp.each do |i| if not (i.children.first) then @leafs[@leafs.size] = i end end return @leafs end private
def looping(y, parent) t = Array.new t = parent.children t.each do |i| y[y.size] = i if i.children.first then looping(y, i) end end end end end end end

RichardK avatar Sep 19 '10 15:09 RichardK

A variant could be passing an array instead of knot as object; so that the default could be knot.root ...

RichardK avatar Sep 19 '10 15:09 RichardK