Class: Rack::PrettyJSON

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/pretty_json.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ PrettyJSON

You can customize the behavior of ‘Rack::PrettyJSON` with the options hash.

Parameters:

  • app (#call)

    A Rack middleware or endpoint

  • options (Hash<Symbol => Boolean, String>) (defaults to: {})

    a configuration hash



13
14
15
16
17
18
19
# File 'lib/rack/pretty_json.rb', line 13

def initialize(app, options = {})
  @app = app
  @options = {
    :always => false,
    :with_paramater => 'pretty'
  }.merge(options)
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rack/pretty_json.rb', line 21

def call(env)
  status, headers, body = @app.call(env)
  headers = Rack::Utils::HeaderHash.new(headers)
  query_hash = Rack::Utils.parse_nested_query(env['QUERY_STRING'])

  # If this is a JSON response..
  if headers['Content-Type'].to_s.scan('application/json').size > 0
    # AND if ANY of the following are true:
    # - we've been configured to process all JSON responses
    # - pretty json format has been requested
    # - we're in development mode
    if always_process? || requsted_pretty_version?(query_hash) || development?
      body_io = ::StringIO.new
      body.each { |line| body_io << line }

      body = ::StringIO.new make_pretty!(body_io.string)
    end
  end

  [status, headers, body]
end