I want to render a jbuilder template like this:
json.author do
json.partial! 'user', user: @user
end
json.owner do
json.partial! 'user', user: @user
end
It seems a waste to render one partial twice, can I render like this?
user_json = json.some_render_partial! 'user', user: @user
json.author { user_json }
json.owner { user_json }
It seems a waste to render one partial twice, can I render like this?
If your concern is to minimize code then yes, you can using proc
s.
user_json = proc { json.partial! 'user', user: @user }
json.author &user_json
json.owner &user_json
Also, if your concern is to boost performance, then one way is to cache your partial. Try this
user_json = proc {
json.cache! @user, expires_in: 10.minutes do
json.partial! 'user', user: @user
end
}
json.author &user_json
json.owner &user_json
But, sometimes caching can be slower instead. So, keep in mind if it meets the following criteria:
Partial encompasses hefty computation that are on average more expensive than accessing cache. like WEB API Calls or AR queries
The size of the JSON blob produced is small
See this for more info [ Jbuilder Rails caching is slower ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With