You may get into a situation where you’d rather get the Hash from jBuilder rather than a string of JSON.
For example, you might normally get the JSON string like this in your controller method:
data = render_to_string(
template: "/api/v1/comments/show.json.jbuilder",
locals: { comment: @comment},
format: :json
)
And the show.json.jbuilder
json.partial! "/api/v1/comments/comment.json.jbuilder", comment: @comment
You could instead do this:
data_hash = JbuilderTemplate.new(view_context) do |json|
json.partial! "/api/v1/comments/comment.json.jbuilder", comment: @comment
end.attributes!
json = data_hash.to_json
Notice for the 2nd one:
- We’re rendering a partial, and setting the value of the local variable comment, as is done for the
show.json.jbuilder
view. -
attributes!
converts the object into the Hash. Then callingto_json
on the Hash will convert it back to json.
The results are not going to be 100% identical as some empiracal results show that Jbuilder render_to_string will round off decimals at 10 digits, whereas calling data_hash.to_json
gave us 13 digits of precision.
If you need to combine the result of several Jbuilder partials, then this technique to get a Hash should be quite useful. For example, you can combine the hashes and create a new result.
hash = JbuilderTemplate.new(view_context) do |json|
json.partial! "/path/to/partial", local_var: local_var_value
end.attributes!