Sha256: 6cc76f0ad91ba6804647a6a61fd19824aaffb55e7faac138fb353210953b9016

Contents?: true

Size: 1.19 KB

Versions: 13

Compression:

Stored size: 1.19 KB

Contents

require 'rest-core/middleware'
require 'rest-core/util/json'

class RestCore::JsonResponse
  def self.members; [:json_response]; end
  include RestCore::Middleware

  class ParseError < Json.const_get(:ParseError)
    attr_reader :cause, :body
    def initialize cause, body
      msg = cause.message.force_encoding('utf-8')
      super("#{msg}\nOriginal text: #{body}")
      @cause, @body = cause, body
    end
  end

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

  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

  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
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rest-core-3.6.0 lib/rest-core/middleware/json_response.rb
rest-core-3.5.92 lib/rest-core/middleware/json_response.rb
rest-core-3.5.91 lib/rest-core/middleware/json_response.rb
rest-core-3.5.9 lib/rest-core/middleware/json_response.rb
rest-core-3.5.8 lib/rest-core/middleware/json_response.rb
rest-core-3.5.7 lib/rest-core/middleware/json_response.rb
rest-core-3.5.6 lib/rest-core/middleware/json_response.rb
rest-core-3.5.4 lib/rest-core/middleware/json_response.rb
rest-core-3.5.3 lib/rest-core/middleware/json_response.rb
rest-core-3.5.2 lib/rest-core/middleware/json_response.rb
rest-core-3.5.1 lib/rest-core/middleware/json_response.rb
rest-core-3.5.0 lib/rest-core/middleware/json_response.rb
rest-core-3.3.0 lib/rest-core/middleware/json_response.rb