class MyJohnDeereApi::Request::Collection::Base

Attributes

associations[R]
client[R]

Public Class Methods

new(client, associations = {}) click to toggle source

client is the original client instance which contains the necessary config info.

# File lib/my_john_deere_api/request/collection/base.rb, line 12
def initialize(client, associations = {})
  @client = client
  @associations = associations
  @items = []
end

Public Instance Methods

all() click to toggle source

Return all objects in the collection at once

# File lib/my_john_deere_api/request/collection/base.rb, line 32
def all
  return @all if defined?(@all)
  @all = map { |i| i }
end
count() click to toggle source

Total count of records, even before pagination

# File lib/my_john_deere_api/request/collection/base.rb, line 40
def count
  @count ||= first_page['total']
end
each(&block) click to toggle source

Iterate lazily through all records in the collection, fetching additional pages as needed.

# File lib/my_john_deere_api/request/collection/base.rb, line 22
def each(&block)
  count.times do |index|
    fetch if @items.size <= index
    block.call(@items[index])
  end
end

Private Instance Methods

add_items_from_page(page) click to toggle source
# File lib/my_john_deere_api/request/collection/base.rb, line 67
def add_items_from_page(page)
  @items += page['values'].map{|record| model.new(client, record) }
end
extract_page_contents(page) click to toggle source
# File lib/my_john_deere_api/request/collection/base.rb, line 62
def extract_page_contents(page)
  add_items_from_page(page)
  set_next_page(page)
end
fetch() click to toggle source
# File lib/my_john_deere_api/request/collection/base.rb, line 55
def fetch
  return unless @next_page

  page = client.get(@next_page)
  extract_page_contents(page)
end
first_page() click to toggle source
# File lib/my_john_deere_api/request/collection/base.rb, line 46
def first_page
  return @first_page if defined?(@first_page)

  @first_page = client.get(resource)
  extract_page_contents(@first_page)

  @first_page
end
set_next_page(page) click to toggle source
# File lib/my_john_deere_api/request/collection/base.rb, line 71
def set_next_page(page)
  if next_page = page['links'].detect{|link| link['rel'] == 'nextPage'}
    @next_page = uri_path(next_page['uri'])
  else
    @next_page = nil
  end
end