Skip to content

Instantly share code, notes, and snippets.

@iaintshine
Last active December 30, 2015 00:39
Show Gist options
  • Save iaintshine/7750708 to your computer and use it in GitHub Desktop.
Save iaintshine/7750708 to your computer and use it in GitHub Desktop.
Rack middleware for pretty printing json responses and sample Rails usage
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
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