Class: Shoptet::ApiEnumerator

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/shoptet/api_enumerator.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_url, filters, data_key, api) ⇒ ApiEnumerator

Returns a new instance of ApiEnumerator.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/shoptet/api_enumerator.rb', line 5

def initialize base_url, filters, data_key, api
  @base_url = base_url
  @filters = filters
  @data_key = data_key || URI(base_url).path.split('/').last
  @api = api

  @enum = Enumerator.new do |y|
    first_page.dig('data', @data_key).each { y.yield _1 }

    if total_pages > 1
      (2..(total_pages - 1)).each do |page|
        @api.get(base_url, filters.merge(page: page))
          .dig('data', @data_key)
          .each { y.yield _1 }
      end

      last_page.dig('data', @data_key).each { y.yield _1 }
    end
  end

  super @enum
end

Instance Method Details

#first_pageObject



28
29
30
# File 'lib/shoptet/api_enumerator.rb', line 28

def first_page
  @first_page ||= @api.get(@base_url, @filters)
end

#last_pageObject



32
33
34
35
36
# File 'lib/shoptet/api_enumerator.rb', line 32

def last_page
  return first_page if total_pages < 2

  @last_page ||= @api.get(@base_url, @filters.merge(page: total_pages))
end

#sizeObject



42
43
44
# File 'lib/shoptet/api_enumerator.rb', line 42

def size
  first_page.dig('data', 'paginator', 'totalCount')
end

#total_pagesObject



38
39
40
# File 'lib/shoptet/api_enumerator.rb', line 38

def total_pages
  first_page.dig('data', 'paginator', 'pageCount') || 0
end