Using partial with a dynamic name
Hello,
In my application, I want to render a template with a dynamic name. The goal is to render a recursive structure, for a Javascript tree plugin.
Here is the template rendered by Gon.
json.tree do
@elements.each do |element|
json.set!(element.name) do
ojbect_name = element.class.to_s.underscore # 'folder' or 'document'.
json.partial!("intranet/documents/#{ojbect_name}", ojbect_name.to_sym => element)
end
end
end
Reading the source code, I have seen multiple reasons preventing it from working:
- Gon tests the path statically (performing no interpolation) ;
- Gon supports only name with 1 or 2 components (foo or foo/bar, no foo/bar/baz) ;
Then, even with a more statical approach like:
json.tree do
@elements.each do |element|
json.set!(element.name) do
object_name = element.class.to_s.underscore
if object_name == 'folder'
json.partial! 'app/views/intranet/documents/_folder.json.jbuilder', folder: element
else
json.partial! 'app/views/intranet/documents/_document.json.jbuilder', document: element
end
end
end
end
It still doesn't work since the eval in set_options_from_hash can't find local variable.
What do you suggest for cases like this?
I would be glad to contribute to Gon for it to be more dynamic, but it's a hard topic on which I have not much leads. Do you have projects about that or leads for me to work on it?
Hello! Interesting case! Yeah, gon jbuilder now is not really dynamic and fully compatible. I think we can try to do something like done here https://github.com/gazay/gon/blob/master/lib/gon/jbuilder.rb#L61. But I'm not sure yet.