Using jbuilder for customize json views is a great experience. also I have been writing the jbuilder in a long way. just today i found shortcuts way to write the same this. The length of the code dramatically reduced. Plus jbuilder support for partial is the best thing one could dream of.
previously the my code to render the array of books was was like this.
json.data do json.books @books do |book| json.id book.id json.name book.name json.author book.author json.condition book.condition json.genere book.genere json.grade book.grade json.price book.price json.publication book.publication json.latitude book.latitude json.longitude book.longitude json.address book.address json.donate book.donate json.exchange book.exchange end end
Then I found the shortcut way for the same thing.
json.data do json.books @books do |book| json.(book, :id, :name, :author, :condition, :genere, :grade, :price, :publication, :latitude, :longitude, :address, :donate, :exchange) end end
See that large chunk reduced to simple lines. Just Wow.. 🙂
then I wrote a partial for that book Under the name _book.json.jbuilder
json.(book, :id, :name, :author, :condition, :genere, :grade, :price, :publication, :latitude, :longitude, :address, :donate, :exchange)
and in index.jbuilder.json
json.data do json.books @books do |book| json.partial! book end end
and thats it. The same partial can be reuse in index, create, update and delete views.
and the magic is that if we have to add or change any attribute, just do it in partial. all views will automically updated. yeeaa 😀