Permalink
Browse files

Added arrange_serializable

  • Loading branch information...
1 parent 1fb1c1d commit e56807e97111dcb6b178dfcabd1b0abf1081462e Kris Handley committed with Stefan Kroes Nov 20, 2013
Showing with 37 additions and 0 deletions.
  1. +16 −0 README.rdoc
  2. +7 −0 lib/ancestry/class_methods.rb
  3. +14 −0 test/has_ancestry_test.rb
View
16 README.rdoc
@@ -156,6 +156,22 @@ The arrange method takes ActiveRecord find options. If you want your hashes to b
TreeNode.find_by_name('Crunchy').subtree.arrange(:order => :name)
+To get the arranged nodes as a nested array of hashes for serialization:
+
+ TreeNode.arrange_serializable
+
+ [
+ {
+ "ancestry" => nil, "id" => 1, "children" => [
+ { "ancestry" => "1", "id" => 2, "children" => [] }
+ ]
+ }
+ ]
+
+The result of arrange_serializable can easily be serialized to json with 'to_json', or some other format:
+
+ TreeNode.arrange_serializable.to_json
+
= Sorting
If you just want to sort an array of nodes as if you were traversing them in preorder, you can use the sort_by_ancestry class method:
View
7 lib/ancestry/class_methods.rb
@@ -55,6 +55,13 @@ def arrange_nodes(nodes)
arranged_nodes
end
end
+
+ # Arrangement to nested array
+ def arrange_serializable nodes = arrange
+ nodes.map do |parent, children|
+ parent.serializable_hash.merge 'children' => arrange_serializable(children)
+ end
+ end
# Pseudo-preordered array of nodes. Children will always follow parents,
# for ordering nodes within a rank provide block, eg. Node.sort_by_ancestry(Node.all) {|a, b| a.rank <=> b.rank}.
View
14 test/has_ancestry_test.rb
@@ -429,6 +429,20 @@ def test_arrangement
end
end
+ def test_arrange_serializable
+ AncestryTestDatabase.with_model :depth => 2, :width => 1 do |model, roots|
+ result = [
+ {
+ 'ancestry' => nil, 'id' => 1, 'children' => [
+ { 'ancestry' => '1', 'id' => 2, 'children' => [] }
+ ]
+ }
+ ]
+
+ assert_equal model.arrange_serializable, result
+ end
+ end
+
def test_node_creation_though_scope
AncestryTestDatabase.with_model do |model|
node = model.create!

0 comments on commit e56807e

Please sign in to comment.