Class: RedditKit::Response::ParseJSON

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/redditkit/response/parse_json.rb

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



21
22
23
24
25
# File 'lib/redditkit/response/parse_json.rb', line 21

def on_complete(env)
  if respond_to?(:parse)
    env[:body] = parse(env[:body]) unless [204, 301, 302, 304].include?(env[:status])
  end
end

#parse(body) ⇒ Object

Note:

Because the reddit API sometimes returns invalid JSON objects with an application/json header, we want to return the body itself if the JSON parsing fails, because the response is still likely useful.

Turn the response body into a JSON object.



15
16
17
18
19
# File 'lib/redditkit/response/parse_json.rb', line 15

def parse(body)
  MultiJson.load(body, :symbolize_keys => true) unless body.nil?
rescue MultiJson::LoadError
  body
end