Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I render one partial twice in jbuilder?

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 }
like image 507
Tony Han Avatar asked Dec 02 '14 08:12

Tony Han


1 Answers

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 procs.

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 ]

like image 153
illusionist Avatar answered Sep 27 '22 23:09

illusionist