Class: Quandl::Client::Middleware::ParseJSON

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/quandl/client/middleware/parse_json.rb

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/quandl/client/middleware/parse_json.rb', line 7

def on_complete(env)
  env[:body] = case env[:status]
  when 204
    parse('{}', env)
  else
    parse(env[:body], env)
  end
end

#parse(body, env) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/quandl/client/middleware/parse_json.rb', line 16

def parse(body, env)
  json = parse_json(body)
  errors = json.delete(:errors) || {}
   = json.delete(:metadata) || {}
  # collect some response data
  .merge!({
    status:                 env[:status],
    headers:                env[:response_headers],
    })
  # return object
  object = {
    :data => json,
    :errors => errors,
    :metadata => 
  }
  env[:status] = 200
  object
end

#parse_json(body = nil) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/quandl/client/middleware/parse_json.rb', line 35

def parse_json(body = nil)
  body ||= '{}'
  message = "Response from the API must behave like a Hash or an Array (last JSON response was #{body.inspect})"

  json = begin
    Yajl.load(body, :symbolize_keys => true)
  rescue Yajl::ParseError
    { id: 1, errors: { parse_error: message } }
    
    # raise Her::Errors::ParseError, message
  end
  # raise Her::Errors::ParseError, message unless json.is_a?(Hash) or json.is_a?(Array)

  json
end