Permalink
Browse files

Backport ClassMethods#to_a and InstanceMethods#to_a as to_nested_a"

  • Loading branch information...
1 parent 57f26ee commit 46adf10665750f8cd951a976c4d6b89d424cbcbb Paweł Kondzior committed Jan 10, 2009
Showing with 36 additions and 0 deletions.
  1. +35 −0 lib/sequel_nested_set.rb
  2. +1 −0 spec/nested_set_spec.rb
View
35 lib/sequel_nested_set.rb
@@ -212,6 +212,22 @@ def to_text(&block)
end
text.join("\n")
end
+
+ # Returns the entire set as a nested array. If flat is true then a flat
+ # array is returned instead. Specify mover to exclude any impossible
+ # moves. Pass a block to perform an operation on each item. The block
+ # arguments are |item, level|.
+ def to_nested_a(flat = false, mover = nil, &block)
+ descendants = self.nested.all
+ array = []
+
+ while not descendants.empty?
+ items = descendants.shift.to_nested_a(flat, mover, descendants, 0, &block)
+ array.send flat ? 'concat' : '<<', items
+ end
+
+ return array
+ end
end
module InstanceMethods
@@ -421,6 +437,25 @@ def to_text
end.join("\n")
end
+ # Returns self and its descendants as a nested array. If flat is true
+ # then a flat array is returned instead. Specify mover to exclude any
+ # impossible moves. Pass a block to perform an operation on each item.
+ # The block arguments are |item, level|. The remaining arguments for
+ # this method are for recursion and should not normally be given.
+ def to_nested_a(flat = false, mover = nil, descendants = nil, level = self.level, &block)
+ descendants ||= self.descendants
+ array = [ block_given? ? yield(self, level) : self ]
+
+ while not descendants.empty?
+ break unless descendants.first.parent_id == self.id
+ item = descendants.shift
+ items = item.to_nested_a(flat, mover, descendants, level + 1, &block)
+ array.send flat ? 'concat' : '<<', items if mover.nil? or mover.new? or mover.move_possible?(item)
+ end
+
+ return array
+ end
+
protected
# on creation, set automatically lft and rgt to the end of the tree
def set_default_left_and_right
View
1 spec/nested_set_spec.rb
@@ -17,6 +17,7 @@
describe "ClassMethods" do
it "should have nested_set_options" do
+ debugger
Client.should respond_to(:nested_set_options)
end

0 comments on commit 46adf10

Please sign in to comment.