class FaradayJSON::ParseJson

Public: Parse response bodies as JSON.

Constants

CONTENT_TYPE

Private Class Methods

new(app = nil, options = {}) click to toggle source
Calls superclass method
# File lib/faraday_json/parse_json.rb, line 22
def initialize(app = nil, options = {})
  super(app)
  @options = options
  @content_types = Array(options[:content_type])
end

Private Instance Methods

call(environment) click to toggle source
# File lib/faraday_json/parse_json.rb, line 28
def call(environment)
  @app.call(environment).on_complete do |env|
    if process_response_type?(response_type(env)) and parse_response?(env)
      process_response(env)
    end
  end
end
parse_response?(env) click to toggle source
# File lib/faraday_json/parse_json.rb, line 86
def parse_response?(env)
  env[:body].respond_to? :to_str
end
preserve_raw?(env) click to toggle source
# File lib/faraday_json/parse_json.rb, line 90
def preserve_raw?(env)
  env[:request].fetch(:preserve_raw, @options[:preserve_raw])
end
process_response(env) click to toggle source
# File lib/faraday_json/parse_json.rb, line 36
def process_response(env)
  env[:raw_body] = env[:body] if preserve_raw?(env)
  body = env[:body]

  # Body will be in an unknown encoding. Use charset field to coerce it to
  # internal UTF-8.
  charset = response_charset(env)

  # We must ensure we're interpreting the body as the right charset. First,
  # strip the BOM (if any).
  body = strip_bom(body, charset, { 'default_encoding' => 'us-ascii' })

  # Transcode to UTF-8
  body = to_utf8(body, charset, { 'force_input_charset' => true })

  # Now that's done, parse the JSON.
  ret = nil
  begin
    ret = ::JSON.parse(body) unless body.strip.empty?
  rescue StandardError, SyntaxError => err
    raise err if err.is_a? SyntaxError and err.class.name != 'Psych::SyntaxError'
    raise Faraday::Error::ParsingError, err
  end
  env[:body] = ret
end
process_response_type?(type) click to toggle source
# File lib/faraday_json/parse_json.rb, line 80
def process_response_type?(type)
  @content_types.empty? or @content_types.any? { |pattern|
    pattern.is_a?(Regexp) ? type =~ pattern : type == pattern
  }
end
response_charset(env) click to toggle source
# File lib/faraday_json/parse_json.rb, line 68
def response_charset(env)
  header = env[:response_headers][CONTENT_TYPE].to_s
  if header.index(';')
    header.split(';').each do |part|
      if part.index('charset=')
        return part.split('charset=', 2).last
      end
    end
  end
  return nil
end
response_type(env) click to toggle source
# File lib/faraday_json/parse_json.rb, line 62
def response_type(env)
  type = env[:response_headers][CONTENT_TYPE].to_s
  type = type.split(';', 2).first if type.index(';')
  type
end