Class: PriceGrabber::Response

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/pricegrabber/response.rb

Overview

Represents a response from the PriceGrabber API.

Instance Method Summary collapse

Constructor Details

#initialize(response, wants) ⇒ Response

Returns a new instance of Response.

Parameters:

  • response (HTTPI::Response)

    The XML response from Pricegrabber’s API

  • wants (Array<String>)

    Attributes from the response that should be made available within this response



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pricegrabber/response.rb', line 10

def initialize(response, wants)
  @status = response.code
  resp_hash = Hash.from_xml(response.body)
  @error = resp_hash["document"]["error"]
  @results = []
  [resp_hash["document"]["product"]].flatten.each do |product|
    curr_result = ResponseItem.with_attributes(wants)
    wants.map do |want|
      parts = want.split(".")
      curr = parts.shift
      curr_value = product
      while curr && curr_value
        curr_value = curr_value[curr]
        curr = parts.shift
      end

      curr_result.public_send(:"#{want.tr(".", "_")}=", curr_value)
    end
    @results << curr_result
  end
end

Instance Method Details

#each(*args, &block) ⇒ Object



32
33
34
# File 'lib/pricegrabber/response.rb', line 32

def each(*args, &block)
  @results.each(*args, &block)
end

#successful?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/pricegrabber/response.rb', line 36

def successful?
  @status < 300 && @status >= 200 && @error == nil
end