Class: Ridley::Middleware::ParseJson

Inherits:
Faraday::Response::Middleware
  • Object
show all
Extended by:
Logging
Includes:
Logging
Defined in:
lib/ridley/middleware/parse_json.rb

Constant Summary collapse

JSON_TYPE =
'application/json'.freeze
BRACKETS =
[ 
  "[",
  "{"
].freeze
WHITESPACE =
[
  " ",
  "\n",
  "\r",
  "\t"
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

logger, logger, set_logger

Class Method Details

.json_response?(env) ⇒ Boolean

Determines if the response of the given Faraday request env contains JSON


69
70
71
# File 'lib/ridley/middleware/parse_json.rb', line 69

def json_response?(env)
  response_type(env) == JSON_TYPE && looks_like_json?(env)
end

.looks_like_json?(env) ⇒ Boolean

Examines the body of a request env and returns true if it appears to contain JSON or false if it does not


79
80
81
82
83
# File 'lib/ridley/middleware/parse_json.rb', line 79

def looks_like_json?(env)
  return false unless env[:body].present?

  BRACKETS.include?(first_char(env[:body]))
end

.parse(body) ⇒ Hash

Takes a string containing JSON and converts it to a Ruby hash symbols for keys


30
31
32
33
# File 'lib/ridley/middleware/parse_json.rb', line 30

def parse(body)
  result = MultiJson.decode(body)
  result.is_a?(Hash) ? Hashie::Mash.new(result) : result
end

.response_type(env) ⇒ String

Extracts the type of the response from the response headers of a Faraday request env. 'text/html' will be returned if no content-type is specified in the response

Examples:

env = {
  :response_headers => {
    'content-type' => 'text/html; charset=utf-8'
  }
  ...
}

ParseJson.response_type(env) => 'application/json'

53
54
55
56
57
58
59
60
# File 'lib/ridley/middleware/parse_json.rb', line 53

def response_type(env)
  if env[:response_headers][CONTENT_TYPE].nil?
    log.debug { "response did not specify a content type" }
    return "text/html"
  end

  env[:response_headers][CONTENT_TYPE].split(';', 2).first
end

Instance Method Details

#on_complete(env) ⇒ Object


98
99
100
101
102
103
104
105
106
107
# File 'lib/ridley/middleware/parse_json.rb', line 98

def on_complete(env)
  log.debug(env)

  if self.class.json_response?(env)
    log.debug { "==> parsing Chef response body as JSON" }
    env[:body] = self.class.parse(env[:body])
  else
    log.debug { "==> Chef response did not contain a JSON body" }
  end
end