Class: AmazonProduct::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/amazon_product/response.rb

Overview

A wrapper around the API response.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body, code) ⇒ Response

Returns a new instance of Response.



11
12
13
14
# File 'lib/amazon_product/response.rb', line 11

def initialize(body, code)
  @body = body
  @code = code.to_i
end

Instance Attribute Details

#bodyObject

The response body.



6
7
8
# File 'lib/amazon_product/response.rb', line 6

def body
  @body
end

#codeObject

The HTTP status code of the response.



9
10
11
# File 'lib/amazon_product/response.rb', line 9

def code
  @code
end

Instance Method Details

#each(path, &block) ⇒ Object

A shorthand that queries for a specified attribute and yields to a given block each matching document.

response.each('Item') { |item| puts item }


21
22
23
# File 'lib/amazon_product/response.rb', line 21

def each(path, &block)
  find(path).each { |match| block.call(match) }
end

#errorsObject

An array of errors in the response.



26
27
28
# File 'lib/amazon_product/response.rb', line 26

def errors
  find('Error')
end

#find(attribute) ⇒ Object Also known as: []

Queries for a specified attribute and returns an array of matching documents.

items = response.find('Item')


35
36
37
# File 'lib/amazon_product/response.rb', line 35

def find(attribute)
  xml.xpath("//xmlns:#{attribute}").map { |e| Builder.from_xml(e) }
end

#has_errors?Boolean

Returns true if the response contains errors.

Returns:

  • (Boolean)


41
42
43
# File 'lib/amazon_product/response.rb', line 41

def has_errors?
  errors.count > 0
end

#map(path, &block) ⇒ Object

A shorthand that queries for a specifed attribute, yields to a given block matching documents, and collects final values.

items = response.map('Item') { |item| # do something }


50
51
52
# File 'lib/amazon_product/response.rb', line 50

def map(path, &block)
  find(path).map { |match| block.call(match) }
end

#to_hashObject

Parses the response into a simple hash.



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

def to_hash
  Builder.from_xml(xml)
end

#valid?Boolean

Checks if the HTTP response is OK.

Returns:

  • (Boolean)


60
61
62
# File 'lib/amazon_product/response.rb', line 60

def valid?
  code == 200
end

#xmlObject

The XML document.



65
66
67
# File 'lib/amazon_product/response.rb', line 65

def xml
  @xml ||= Nokogiri::XML(@body)
end