Extensions for acts_as_tree
Filed in: Rails, Ruby Add comments
While the acts_as_tree rails plugin ( http://dev.rubyonrails.com/svn/rails/plugins/acts_as_tree ) provides some basic methods for accessing tree like data structure, I found that it lacks some basic ones, for example – has_children? and has_siblings?
Other than that, it would have been nice to know the tree width and depth (especially if you need to draw it, and need to calculate the scaling.
module ActiveRecord module Acts module Tree module InstanceMethods def has_children? !self.children.size.zero? end def has_siblings? !self.siblings.size.zero? end # Return the tree depth def depth return 0 unless has_children? children.inject(0) {|dep,c| dep > c.depth ? dep : c.depth} + 1 end # Return the tree width def width return 1 unless has_children? children.inject(0) {|sum,c| sum + c.width} end end end end end |
Maybe if I won’t be lazy, I’ll write some tests and send this for inclusion in the plugin…