Permalink
Browse files

give arrange_serializable the ability to take an options hash

  • Loading branch information...
1 parent ad2a8c5 commit 4cd51a195edfa5efe6fb699e9b86e99b68a001d6 Sara Trice committed Nov 27, 2013
Showing with 21 additions and 13 deletions.
  1. +4 −0 README.rdoc
  2. +4 −3 lib/ancestry/class_methods.rb
  3. +13 −10 test/has_ancestry_test.rb
View
@@ -172,6 +172,10 @@ The result of arrange_serializable can easily be serialized to json with 'to_jso
TreeNode.arrange_serializable.to_json
+You can also pass the order to the arrange_serializable method just as you can pass it to the arrange method:
+
+ TreeNode.arrange_serializable(:order => :name)
+
= 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:
@@ -56,10 +56,11 @@ def arrange_nodes(nodes)
end
end
- # Arrangement to nested array
- def arrange_serializable nodes = arrange
+ # Arrangement to nested array
+ def arrange_serializable options={}, nodes=nil
+ nodes = arrange(options) if nodes.nil?
nodes.map do |parent, children|
- parent.serializable_hash.merge 'children' => arrange_serializable(children)
+ parent.serializable_hash.merge 'children' => arrange_serializable(options, children)
end
end
@@ -430,16 +430,19 @@ def test_arrangement
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
+ AncestryTestDatabase.with_model :depth => 2, :width => 2 do |model, roots|
+ result = [{"ancestry"=>nil,
+ "id"=>4,
+ "children"=>
+ [{"ancestry"=>"4", "id"=>6, "children"=>[]},
+ {"ancestry"=>"4", "id"=>5, "children"=>[]}]},
+ {"ancestry"=>nil,
+ "id"=>1,
+ "children"=>
+ [{"ancestry"=>"1", "id"=>3, "children"=>[]},
+ {"ancestry"=>"1", "id"=>2, "children"=>[]}]}]
+
+ assert_equal model.arrange_serializable(order: "id desc"), result
end
end

0 comments on commit 4cd51a1

Please sign in to comment.