Module: Uploadcare::Entity::Decorator::Paginator

Included in:
FileList, GroupList
Defined in:
lib/uploadcare/entity/decorator/paginator.rb

Overview

provides pagination methods for things in Uploadcare that paginate, namely [FileList] and [Group]

Requirements:

  • Should be Entity with Client
  • Associated Client should have list method that returns objects with pagination
  • Response should have :next, :previous, :total, :per_page params and :results fields

Instance Method Summary collapse

Instance Method Details

#allArray

Load and return all objects in list

Returns:

  • (Array)


73
74
75
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 73

def all
  load[:results]
end

#each {|Block| ... } ⇒ Object

iterate through pages, starting with current one

Yields:

  • (Block)


62
63
64
65
66
67
68
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 62

def each(&block)
  current_page = self
  while current_page
    current_page.results.each(&block)
    current_page = current_page.next_page
  end
end

#loadObject

Attempts to load the entire list after offset into results of current object

It's possible to avoid loading objects on previous pages by offsetting them first



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 46

def load
  return self if @entity[:next].nil? || @entity[:results].length == @entity[:total]

  np = self
  until np.next.nil?
    np = np.next_page
    @entity[:results].concat(np.results.map(&:to_h))
  end
  @entity[:next] = nil
  @entity[:per_page] = @entity[:total]
  self
end

#metaObject

meta data of a pagination object



18
19
20
21
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 18

def meta
  Hashie::Mash.new(next: @entity[:next], previous: @entity[:previous],
                   total: @entity[:total], per_page: @entity[:per_page])
end

#next_pageObject

Returns new instance of current object on next page



24
25
26
27
28
29
30
31
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 24

def next_page
  url = @entity[:next]
  return unless url

  query = URI.decode_www_form(URI(url).query).to_h
  query = query.to_h { |k, v| [k.to_sym, v] }
  self.class.list(**query)
end

#previous_pageObject

Returns new instance of current object on previous page



34
35
36
37
38
39
40
41
# File 'lib/uploadcare/entity/decorator/paginator.rb', line 34

def previous_page
  url = @entity[:previous]
  return unless url

  query = URI.decode_www_form(URI(url).query).to_h
  query = query.to_h { |k, v| [k.to_sym, v] }
  self.class.list(**query)
end