Sha256: 8085031222321b808875488a6bc05ae73f8b5910f888c9c1e3846ad6f2793dc2

Contents?: true

Size: 1.11 KB

Versions: 4

Compression:

Stored size: 1.11 KB

Contents

require 'fassbinder/book_builder'
require 'fassbinder/errors'

module Fassbinder
  class Response
    include Enumerable

    def initialize(response, locale)
      unless response.valid?
        message =
          if response.has_errors?
            response.errors.first['Message']
          else
            response.code
          end

        raise InvalidResponse, message
      end

      @response = response
      @locale   = locale.to_sym
    end

    # Yields each snapshot to given block.
    #
    def each(&block)
      @response.each('Item') { |doc| block.call(build_book(doc)) }
    end

    def errors
      @response.errors.map do |error|
        error['Message'].scan(/[0-9A-Z]{10}/).first rescue nil
      end.compact
    end

    private

    def build_book(doc)
      builder = BookBuilder.new

      builder.asin = doc['ASIN']
      builder.offers_total = doc['Offers']['TotalOffers']
      host = Sucker::Request::HOSTS[@locale]
      builder.venue = "amazon.#{host.match(/[^.]+$/)}"

      offers = doc['Offers']['Offer']
      offers.each { |offer| builder.add_offer(offer) }

      builder.book
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
fassbinder-0.0.12 lib/fassbinder/response.rb
fassbinder-0.0.11 lib/fassbinder/response.rb
fassbinder-0.0.10 lib/fassbinder/response.rb
fassbinder-0.0.9 lib/fassbinder/response.rb