Reputation: 51717
I have a tree-like object graph that resembles the following:
{
:name => "Grandparent",
:children => {
:child_a => {
:name => "Parent A",
:children => {
:grandchild_a_a => {
:name => "Child A-A",
:children => {}
}
:grandchild_a_b => {
:name => "Child A-B"
:children => {}
}
}
}
:child_b => {
:name => "Parent B",
:children => {}
}
}
}
I want to generate JSON that mirrors this structure. I don't know how deep the child nesting goes, and the attributes are the same for each level. The keys in the children hash are significant and must be preserved.
I want to use a JBuilder partial to represent a level, and then call it recursively. Here's my template thus far:
# _level_partial.json.jbuilder
# passing the above object graph as :level
json.name level[:name]
json.children do
level[:children].each do |key, child|
# How do I map the following to the given key?
json.partial! "level_partial", :level => child
end
end
I can generate the JSON for each child through the partial call easily enough, but that inserts it directly into the JSON output. How do I map the results of the partial to a particular hash/object key?
Upvotes: 4
Views: 1636
Reputation: 51717
I've found an answer. Although it appears to be largely undocumented, JBuilder.set!
can accept a block instead of an explicit value. That block can call the partial, which is then assigned to the hash.
json.name level[:name]
json.children do
level[:children].each do |key, child|
json.set! key do
json.partial! "level_partial", :level => child
end
end
end
Upvotes: 8