Class: RestCore::JsonResponse

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

Defined Under Namespace

Classes: ParseError

Constant Summary collapse

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

Constants included from Middleware

Middleware::METHODS_WITH_PAYLOAD, Middleware::UNRESERVED

Constants included from RestCore

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Middleware

#contain_binary?, contain_binary?, #error_callback, #escape, escape, #fail, #give_promise, #has_payload?, has_payload?, #id, included, #log, #merge_hash, merge_hash, 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



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

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



30
31
32
33
34
35
36
37
38
# File 'lib/rest-core/middleware/json_response.rb', line 30

def process response
  # StackExchange returns the problematic BOM! in UTF-8, so we need to
  # strip it or it would break JSON parsers (i.e. yajl-ruby and json)
  body = response[RESPONSE_BODY].to_s.sub(/\A\xEF\xBB\xBF/, '')
  response.merge(RESPONSE_BODY => Json.decode("[#{body}]").first)
  # [this].first is not needed for yajl-ruby
rescue Json.const_get(:ParseError) => error
  fail(response, ParseError.new(error, body))
end