Sha256: c011b63ba5cddaa172b4113b53e42ee5db3613ab9d6551f0fc0728beab892498

Contents?: true

Size: 1.79 KB

Versions: 3

Compression:

Stored size: 1.79 KB

Contents

module RakutenWebService
  class SearchResult
    include Enumerable

    def initialize(params, resource_class)
      @params = params.dup
      @resource_class = resource_class
      @client = RakutenWebService::Client.new(resource_class)
    end

    def fetch_result
      query
    end

    def each
      params = @params
      response = query
      loop do
        response.each do |resource|
          yield resource
        end
        break unless response.has_next_page?
        response = query(params.merge('page' => response.page + 1))
      end
    end

    def params
      return {} if @params.nil?
      @params.dup 
    end

    def order(options)
      new_params = @params.dup
      if options.is_a? Hash
        key, sort_order = *(options.to_a.last)
        key = camelize(key.to_s)
        new_params[:sort] = case sort_order.to_s.downcase
                         when 'desc'
                           "-#{key}"
                         when 'asc'
                           "+#{key}"
                         end
      elsif options.to_s == 'standard'
        new_params[:sort] = 'standard' 
      else 
        raise ArgumentError, "Invalid Sort Option: #{options.inspect}"
      end
      self.class.new(new_params, @resource_class)
    end

    private
    def query(params=nil)
      retries = RakutenWebService.configuration.max_retries
      begin 
        @response = @client.get(params || @params)
      rescue RWS::TooManyRequests => e
        if retries > 0
          retries -= 1
          sleep 1
          retry
        else
          raise e
        end
      end
      @response
    end

    def camelize(str)
      str = str.downcase
      str = str.gsub(/([a-z]+)_([a-z]+)/) do
        "#{$1.capitalize}#{$2.capitalize}"
      end
      str[0] = str[0].downcase
      str
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rakuten_web_service-0.6.3 lib/rakuten_web_service/search_result.rb
rakuten_web_service-0.6.2 lib/rakuten_web_service/search_result.rb
rakuten_web_service-0.6.1 lib/rakuten_web_service/search_result.rb