Class: Rack::JsonPrettifier

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/json_prettifier.rb,
lib/rack/json_prettifier/version.rb

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'.freeze
CONTENT_LENGTH =
'Content-Length'.freeze
VERSION =
'0.0.2'

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JsonPrettifier

Returns a new instance of JsonPrettifier.



7
8
9
# File 'lib/rack/json_prettifier.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rack/json_prettifier.rb', line 11

def call(env)
  status, headers, response = @app.call(env)
  if headers[CONTENT_TYPE] =~ /^application\/json/
    obj = JSON.parse(response.body)
    pretty_str = JSON.pretty_unparse(obj)
    response = [pretty_str]
    headers[CONTENT_LENGTH] = Rack::Utils.bytesize(pretty_str).to_s
  end
ensure
  [status, headers, response]
end