Skip to content

Commit

Permalink
Merge pull request #231 from mastfish/allow-arrange-serializable-to-a…
Browse files Browse the repository at this point in the history
…ccept-block-1431492065

Allow arrange serializable to accept block
  • Loading branch information
stefankroes committed May 13, 2015
2 parents 74a0ada + 3173e87 commit 2fa4381
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
17 changes: 17 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@ To get the arranged nodes as a nested array of hashes for serialization:
}
]

You can also supply your own serialization logic using blocks:

For example, using Active Model Serializers:

TreeNode.arrange_serializable do |parent, children|
MySerializer.new(parent, children: children)
end

Or plain hashes:

TreeNode.arrange_serializable do |parent, children|
{
my_id: parent.id
my_children: children
}
end

The result of arrange_serializable can easily be serialized to json with 'to_json', or some other format:

TreeNode.arrange_serializable.to_json
Expand Down
8 changes: 6 additions & 2 deletions lib/ancestry/class_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,14 @@ def arrange_nodes(nodes)
end

# Arrangement to nested array
def arrange_serializable options={}, nodes=nil
def arrange_serializable options={}, nodes=nil, &block
nodes = arrange(options) if nodes.nil?
nodes.map do |parent, children|
parent.serializable_hash.merge 'children' => arrange_serializable(options, children)
if block_given?
yield parent, arrange_serializable(options, children, &block)
else
parent.serializable_hash.merge 'children' => arrange_serializable(options, children)
end
end
end

Expand Down
24 changes: 23 additions & 1 deletion test/concerns/arrangement_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,28 @@ def test_arrange_serializable
end
end

def test_arrange_serializable_with_block
AncestryTestDatabase.with_model :depth => 2, :width => 2 do |model, roots|
expected_result = [{
"id"=>4,
"children"=>
[{"id"=>6},
{"id"=>5}]},
{
"id"=>1,
"children"=>
[{"id"=>3},
{"id"=>2}]}]
result = model.arrange_serializable(order: "id desc") do |parent, children|
out = {}
out["id"] = parent.id
out["children"] = children if children.count > 1
out
end
assert_equal result, expected_result
end
end

def test_arrange_order_option
AncestryTestDatabase.with_model :width => 3, :depth => 3 do |model, roots|
descending_nodes_lvl0 = model.arrange :order => 'id desc'
Expand Down Expand Up @@ -77,4 +99,4 @@ def test_arrangement_nesting
assert_equal 1, model.arrange.count
end
end
end
end

0 comments on commit 2fa4381

Please sign in to comment.