Class: Pandarus::RemoteCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/pandarus/remote_collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(http_client, target_class, path, query_params) ⇒ RemoteCollection

Returns a new instance of RemoteCollection.



5
6
7
8
9
10
11
12
13
14
# File 'lib/pandarus/remote_collection.rb', line 5

def initialize(http_client, target_class, path, query_params)
  @http_client = http_client
  @target_class = target_class
  @path = path
  @cache_pages = query_params[:cache_pages].nil? ? true : query_params[:cache_pages]
  @query_params = query_params.except(:cache_pages)

  @pagination_links = []
  @next_page_cache = {}
end

Instance Method Details

#eachObject



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pandarus/remote_collection.rb', line 20

def each
  if block_given?
    each_page do |page|
      page.each do |member|
        yield(member)
      end
    end
  else
    self.to_enum
  end
end

#each_pageObject



32
33
34
35
36
37
38
39
# File 'lib/pandarus/remote_collection.rb', line 32

def each_page
  if block_given?
    yield first_page
    yield next_page until was_last_page?
  else
    self.to_enum
  end
end

#first_pageObject



41
42
43
44
45
46
47
48
49
# File 'lib/pandarus/remote_collection.rb', line 41

def first_page
  @pagination_links = []
  response = @first_response || @http_client.get do |request|
    request.path = join_paths(base_path, @path)
    request.params = request.params.merge(@query_params) unless @query_params.empty?
  end
  @first_response ||= response if @cache_pages
  handle_response(response)
end

#next_pageObject



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/pandarus/remote_collection.rb', line 51

def next_page
  key = @pagination_links.last.next
  # cache_pages defaults to true, but for massive remote collections
  # keeping everything cached will eventually eat all the available memory
  if @cache_pages
    @next_page_cache[key] ||= @http_client.get(key)
    handle_response @next_page_cache[key]
  else
    handle_response @http_client.get(key)
  end
end

#to_aObject



16
17
18
# File 'lib/pandarus/remote_collection.rb', line 16

def to_a
  each_page.entries.flatten(1)
end