Il modo più semplice è solo per ottenere da Ruby l'analisi dell'intera risposta e sputarla nuovamente utilizzando after_filter
. Prova il seguente codice 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
Se si decide che si desidera che il JSON abbellito invece di minified, è possibile utilizzare questo codice:
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
Oppure, si potrebbe consentire al richiedente di specificare con un parametro:
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
fonte
2013-06-02 12:23:36