Class: RestCore::JsonResponse

Inherits:
Object
  • Object
show all
Includes:
Middleware
Defined in:
lib/rest-core/middleware/json_response.rb

Constant Summary collapse

JSON_RESPONSE_HEADER =
{'Accept' => 'application/json'}.freeze

Constants included from Middleware

Middleware::UNRESERVED

Constants included from RestCore

ASYNC, CLIENT, DRY, FAIL, HIJACK, LOG, PROMISE, REQUEST_HEADERS, REQUEST_METHOD, REQUEST_PATH, REQUEST_PAYLOAD, REQUEST_QUERY, RESPONSE_BODY, RESPONSE_HEADERS, RESPONSE_SOCKET, RESPONSE_STATUS, Simple, TIMER, Universal, VERSION

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Middleware

contain_binary?, #contain_binary?, escape, #escape, #fail, #id, included, #log, #percent_encode, percent_encode, request_uri, #request_uri, #run, #string_keys, string_keys

Methods included from RestCore

eagerload, id

Class Method Details

.membersObject



6
# File 'lib/rest-core/middleware/json_response.rb', line 6

def self.members; [:json_response]; end

Instance Method Details

#call(env, &k) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/rest-core/middleware/json_response.rb', line 11

def call env, &k
  return app.call(env, &k) if env[DRY]
  return app.call(env, &k) unless json_response(env)

  app.call(env.merge(REQUEST_HEADERS =>
    JSON_RESPONSE_HEADER.merge(env[REQUEST_HEADERS]||{}))){ |response|
      yield(process(response))
    }
end

#process(response) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/rest-core/middleware/json_response.rb', line 21

def process response
  response.merge(RESPONSE_BODY =>
    Json.decode("[#{response[RESPONSE_BODY]}]").first)
    # [this].first is not needed for yajl-ruby
rescue Json.const_get(:ParseError) => error
  fail(response, error)
end