Class: Wajub::PagedResult

Inherits:
Object
  • Object
show all
Defined in:
lib/wajub/pagination.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data:, meta:, has_more:, fetch_page:) ⇒ PagedResult

Returns a new instance of PagedResult.



7
8
9
10
11
12
# File 'lib/wajub/pagination.rb', line 7

def initialize(data:, meta:, has_more:, fetch_page:)
  @data = data
  @meta = meta
  @has_more = has_more
  @fetch_page = fetch_page
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



5
6
7
# File 'lib/wajub/pagination.rb', line 5

def data
  @data
end

#has_moreObject (readonly)

Returns the value of attribute has_more.



5
6
7
# File 'lib/wajub/pagination.rb', line 5

def has_more
  @has_more
end

#metaObject (readonly)

Returns the value of attribute meta.



5
6
7
# File 'lib/wajub/pagination.rb', line 5

def meta
  @meta
end

Class Method Details

.create(client, path, plural_key, params = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/wajub/pagination.rb', line 31

def self.create(client, path, plural_key, params = nil)
  params ||= {}
  fetch = lambda do |page_num|
    query = params.merge('page' => page_num)
    res = client.get(path, query)
    list = HttpUtils.pick_list(res, plural_key)
    meta = list[:meta]
    has_more = false
    if meta
      current = meta['current_page'].to_i
      last = meta['last_page'].to_i
      has_more = current < last if current.positive? && last.positive?
    end
    new(data: list[:data], meta: meta, has_more: has_more, fetch_page: fetch)
  end

  page = params['page'] || params[:page] || 1
  fetch.call(page.to_i)
end

Instance Method Details

#auto_paging_each(&block) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/wajub/pagination.rb', line 21

def auto_paging_each(&block)
  page = self
  loop do
    page.data.each(&block)
    break unless page.has_more

    page = page.next_page
  end
end

#next_pageObject

Raises:



14
15
16
17
18
19
# File 'lib/wajub/pagination.rb', line 14

def next_page
  raise WajubError.new('no more pages available', code: 'pagination_error', http_status: 0) unless @has_more

  current = @meta&.fetch('current_page', 1).to_i
  @fetch_page.call(current + 1)
end