Class: Ridley::Middleware::ParseJson
- Inherits:
-
Faraday::Response::Middleware
- Object
- Faraday::Response::Middleware
- Ridley::Middleware::ParseJson
- Defined in:
- lib/ridley/middleware/parse_json.rb
Overview
Constant Summary collapse
- JSON_TYPE =
'application/json'.freeze
- BRACKETS =
[ "[", "{" ].freeze
- WHITESPACE =
[ " ", "\n", "\r", "\t" ].freeze
Class Method Summary collapse
-
.json_response?(env) ⇒ Boolean
Determines if the response of the given Faraday request env contains JSON.
-
.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.
-
.parse(body) ⇒ Hash
Takes a string containing JSON and converts it to a Ruby hash symbols for keys.
-
.response_type(env) ⇒ String
Extracts the type of the response from the response headers of a Faraday request env.
Instance Method Summary collapse
Class Method Details
.json_response?(env) ⇒ Boolean
Determines if the response of the given Faraday request env contains JSON
64 65 66 |
# File 'lib/ridley/middleware/parse_json.rb', line 64 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
74 75 76 77 78 |
# File 'lib/ridley/middleware/parse_json.rb', line 74 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
26 27 28 |
# File 'lib/ridley/middleware/parse_json.rb', line 26 def parse(body) HashWithIndifferentAccess.new MultiJson.decode(body) 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
48 49 50 51 52 53 54 55 |
# File 'lib/ridley/middleware/parse_json.rb', line 48 def response_type(env) if env[:response_headers][CONTENT_TYPE].nil? Ridley.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
93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/ridley/middleware/parse_json.rb', line 93 def on_complete(env) if self.class.json_response?(env) Ridley.log.debug("Parsing JSON Chef Response") Ridley.log.debug(env) env[:body] = self.class.parse(env[:body]) else Ridley.log.debug("Chef Response was not JSON") Ridley.log.debug(env) end end |