Class: GdsApi::Response

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/gds_api/response.rb

Overview

This wraps an HTTP response with a JSON body, and presents this as an object that has the read behaviour of both a Hash and an OpenStruct

Responses can be configured to use relative URLs for ‘web_url` properties. API endpoints should return absolute URLs so that they make sense outside of the GOV.UK context. However on internal systems we want to present relative URLs. By specifying a base URI, this will convert all matching web_urls into relative URLs This is useful on non-canonical frontends, such as those in staging environments. See: github.com/alphagov/wiki/wiki/API-conventions for details on the API conventions

Example:

r = Response.new(response, web_urls_relative_to: "https://www.gov.uk")
r.results[0].web_url
=> "/bank-holidays"

Direct Known Subclasses

ListResponse

Instance Method Summary collapse

Constructor Details

#initialize(http_response, options = {}) ⇒ Response

Returns a new instance of Response.



29
30
31
32
# File 'lib/gds_api/response.rb', line 29

def initialize(http_response, options = {})
  @http_response = http_response
  @web_urls_relative_to = URI.parse(options[:web_urls_relative_to]) if options[:web_urls_relative_to]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method) ⇒ Object



51
52
53
# File 'lib/gds_api/response.rb', line 51

def method_missing(method)
  to_ostruct.send(method)
end

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


60
# File 'lib/gds_api/response.rb', line 60

def blank?; false; end

#codeObject



38
39
40
41
# File 'lib/gds_api/response.rb', line 38

def code
  # Return an integer code for consistency with HTTPErrorResponse
  @http_response.code
end

#present?Boolean

Returns:

  • (Boolean)


59
# File 'lib/gds_api/response.rb', line 59

def present?; true; end

#raw_response_bodyObject



34
35
36
# File 'lib/gds_api/response.rb', line 34

def raw_response_body
  @http_response.body
end

#respond_to_missing?(method, include_private) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/gds_api/response.rb', line 55

def respond_to_missing?(method, include_private)
  to_ostruct.respond_to?(method, include_private)
end

#to_hashObject



43
44
45
# File 'lib/gds_api/response.rb', line 43

def to_hash
  @parsed ||= transform_parsed(JSON.parse(@http_response.body))
end

#to_ostructObject



47
48
49
# File 'lib/gds_api/response.rb', line 47

def to_ostruct
  @ostruct ||= self.class.build_ostruct_recursively(to_hash)
end