Last active
December 30, 2015 00:39
-
-
Save iaintshine/7750708 to your computer and use it in GitHub Desktop.
Rack middleware for pretty printing json responses and sample Rails usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rack' | |
module Rack | |
class PrettyPrint | |
def initialize(app, options = {}) | |
@app, @options = app, options | |
end | |
def call(env) | |
status, headers, response = @app.call(env) | |
if headers['Content-Type'] =~ /^application\/[\w+.-]*json/ && (@options[:force_pretty] || env['QUERY_STRING'].include?("pretty=true")) | |
response = [].tap do |pretty_response| | |
response.each do |chunk| | |
obj = JSON.parse chunk | |
pretty_response << JSON.pretty_unparse(obj) | |
end | |
end | |
headers['Content-Length'] = Rack::Utils.bytesize(response.first).to_s unless response.empty? | |
end | |
[status, headers, response] | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pretty_print' | |
Rails.configuration.middleware.insert_before ActionDispatch::ShowExceptions, Rack::PrettyPrint, force_pretty: Rails.env.development? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment