Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minify JSON output in Rails?

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.

like image 357
Paul Avatar asked Feb 26 '13 17:02

Paul


1 Answers

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
like image 164
Alyssa Ross Avatar answered Sep 22 '22 13:09

Alyssa Ross