Skip to content

Instantly share code, notes, and snippets.

@matflores
Created November 1, 2013 19:28
Show Gist options
  • Save matflores/7270596 to your computer and use it in GitHub Desktop.
Save matflores/7270596 to your computer and use it in GitHub Desktop.
Rack middleware for returning pretty JSON when `pretty` parameter is present and it's not `"false"`.
module Rack
# Prettify JSON responses on demand.
#
#
#
# Builder Usage:
# use Rack::PrettyJSON
#
class PrettyJSON
include Rack::Utils
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
headers = HeaderHash.new(headers)
request = Rack::Request.new(env)
if is_json?(headers) && should_prettify?(request)
response = prettify(response)
# Set new Content-Length, if it was set before we mutated the response body
if headers["Content-Length"]
length = response.to_ary.inject(0) { |len, part| len + bytesize(part) }
headers["Content-Length"] = length.to_s
end
end
[status, headers, response]
end
private
def is_json?(headers)
headers.key?("Content-Type") && headers["Content-Type"].include?("application/json")
end
def should_prettify?(request)
request.params.has_key?("pretty") && !(request.params["pretty"] == "false")
end
def prettify(response)
body = response.inject("") { |body, part| body << part.to_s }
[JSON.pretty_generate(JSON.parse(body))]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment