class Freshsales::Cursor

Attributes

client[R]

Public Class Methods

new(client, path, type, collection_name, args = {}) click to toggle source
# File lib/freshsales/cursor.rb, line 7
def initialize(client, path, type, collection_name, args = {})
  @client = client
  @path       = path
  @type       = type
  @collection_name = collection_name
  @args     = args

  @collection = []
  @page       = params.fetch(:page, 0)
end

Public Instance Methods

each(start = 0) { |element| ... } click to toggle source
# File lib/freshsales/cursor.rb, line 22
def each(start = 0)
  return to_enum(:each, start) unless block_given?

  Array(@collection[start..-1]).each do |element|
    yield(element)
  end

  return if last?

  start = [@collection.size, start].max

  fetch_next_page

  each(start, &Proc.new)
end
params() click to toggle source
# File lib/freshsales/cursor.rb, line 18
def params
  (@args[:params] || {})
end

Private Instance Methods

fetch_next_page() click to toggle source
# File lib/freshsales/cursor.rb, line 46
def fetch_next_page
  nextpage = @page + 1
  @args[:params] = params.merge(page: nextpage)
  response = client.httprequest(:get, @path, @args)
  j = response.body

  # might have been symbolized
  if j.is_a? Hash
    meta = (j['meta'] || j[:meta])
    total_pages = (meta['total_pages'] || meta[:total_pages])
    last = nextpage == total_pages
    logger.debug "Found #{nextpage}/#{total_pages} #{@type} #{@collection_name} (#{j.keys.map { |k| [k, j[k].count] }.join(',')}) last? #{last}"
    data =
      case @type
      when :page
        [j]
      when :elt
        j[@collection_name]
      end
  elsif j.is_a? Array
    # most probably searching
    last = true
    logger.debug "Found #{j.count} elements #{@type} #{@collection_name}"

    data = j
  elsif j.is_a? String
    raise "Unexpected data type received #{j.class}. Are you combining pagination with raw_data? Unsupported for now"
  else
    raise "Unexpected data type received #{j.class}."
  end

  @last_response = last
  @collection += data
  @page = nextpage
end
last?() click to toggle source
# File lib/freshsales/cursor.rb, line 82
def last?
  @last_response
end
logger() click to toggle source
# File lib/freshsales/cursor.rb, line 42
def logger
  @client.logger
end