I am using .json.erb views instead of calling to_json method.
I've found several advices concerning JSON output minification. Ones tell about zipping all the output of web application, others recommend to use after filter
or before render
but they do not explain how to shrink spaces and tabs between JSON elements and where to take JSON input from and where to put the minified result. The third advices tell strictly about minifying JavaScript.
The easiest way is just to get Ruby to parse the whole response and spit it back out again using an after_filter
. Try the following code in app/controllers/application_controller.rb
.
class ApplicationController < ActionController::Base
after_filter :minify_json
private
def minify_json
response.body = JSON.parse(response.body).to_json if request.format.json?
end
end
If you decide that you want the JSON beautified instead of minified, you can use this code:
class ApplicationController < ActionController::Base
after_filter :beautify_json
private
def beautify_json
response.body = JSON.pretty_generate(JSON.parse(response.body)) if request.format.json?
end
end
Or, you could allow the requester to specify using a parameter:
class ApplicationController < ActionController::Base
after_filter :format_json
private
def format_json
if request.format.json?
json = JSON.parse(response.body)
response.body = params[:pretty] ? JSON.pretty_generate(json) : json.to_json
end
end
end
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