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
# 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
  @query_params = query_params

  @pagination_links = []
  @next_page_cache = {}
end

Instance Method Details

#eachObject



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

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



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

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

#first_pageObject



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

def first_page
  @pagination_links = []
  @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
  handle_response(@first_response)
end

#next_pageObject



49
50
51
52
53
# File 'lib/pandarus/remote_collection.rb', line 49

def next_page
  key = @pagination_links.last.next
  @next_page_cache[key] ||= @http_client.get(key)
  handle_response @next_page_cache[key]
end

#to_aObject



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

def to_a
  each_page.entries.flatten(1)
end