Module: Soaspec::ResponseExtractor

Included in:
RestHandler
Defined in:
lib/soaspec/exchange_handlers/response_extractor.rb

Overview

Enables extracting a response according to type / path

Instance Method Summary collapse

Instance Method Details

#extract_hash(response) ⇒ Hash

Convert XML or JSON response into a Hash. Doesn’t accept empty body

Parameters:

  • response (String)

    Response as a String (either in XML or JSON)

Returns:

  • (Hash)

    Extracted Hash from response

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/soaspec/exchange_handlers/response_extractor.rb', line 9

def extract_hash(response)
  raise NoElementAtPath, "Empty Body. Can't assert on it" if response.body.empty?

  case Interpreter.response_type_for response
  when :xml then parse_xml(response.body.to_s)
  when :json
    converted = JSON.parse(response.body)
    return converted.transform_keys_to_symbols if converted.is_a? Hash
    return converted.map!(&:transform_keys_to_symbols) if converted.is_a? Array

    raise Soaspec::ResponseError, 'Incorrect Type produced ' + converted.class
  else
    raise Soaspec::ResponseError, "Neither XML nor JSON detected. It is #{type}. Don't know how to parse It is #{response.body}"
  end
end

#to_hash(response) ⇒ Hash

Returns Hash representing response body.

Parameters:

  • response (Object)

    Response object

Returns:

  • (Hash)

    Hash representing response body



27
28
29
30
31
32
33
34
35
# File 'lib/soaspec/exchange_handlers/response_extractor.rb', line 27

def to_hash(response)
  case Interpreter.response_type_for(response)
  when :xml then IndifferentHash.new(parse_xml(response.body.to_s))
  when :json
    IndifferentHash.new(JSON.parse(response.body.to_s))
  else
    raise "Unable to interpret type of '#{response.body}'. Could be because of: #{Interpreter.diagnose_error}"
  end
end