Module: Hungry::Collection::Pagination

Defined in:
lib/hungry/collection/pagination.rb

Defined Under Namespace

Classes: NotPaginatedError

Instance Method Summary collapse

Instance Method Details

#current_pageObject



55
56
57
58
59
60
61
# File 'lib/hungry/collection/pagination.rb', line 55

def current_page
  if paginated?
    pagination['current_page'].to_i
  else
    1
  end
end

#first(n = 1) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/hungry/collection/pagination.rb', line 10

def first(n = 1)
  scope   = all(per_page: n, page: 1)
  results = scope.results
  
  if n == 1 && (value = results.first)
    resource = klass.new results.first
    resource.data_source = scope.data_source
    resource
  elsif n > 1
    results.first(n).map do |result|
      resource = klass.new result
      resource.data_source = scope.data_source
      resource
    end
  end
end

#nextObject

Raises:



76
77
78
79
# File 'lib/hungry/collection/pagination.rb', line 76

def next
  raise NotPaginatedError unless paginated?
  all page: next_page if next_page
end

#next_pageObject



67
68
69
# File 'lib/hungry/collection/pagination.rb', line 67

def next_page
  current_page + 1 if paginated? && current_page < total_pages
end

#paginate(page, options = {}) ⇒ Object



6
7
8
# File 'lib/hungry/collection/pagination.rb', line 6

def paginate(page, options = {})
  all options.merge(page: page)
end

#paginated?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/hungry/collection/pagination.rb', line 27

def paginated?
  pagination.present?
end

#per_pageObject



31
32
33
34
35
36
37
# File 'lib/hungry/collection/pagination.rb', line 31

def per_page
  if paginated?
    pagination['per_page'].to_i
  else
    response['results'].length
  end
end

#previousObject

Raises:



71
72
73
74
# File 'lib/hungry/collection/pagination.rb', line 71

def previous
  raise NotPaginatedError unless paginated?
  all page: previous_page if previous_page
end

#previous_pageObject



63
64
65
# File 'lib/hungry/collection/pagination.rb', line 63

def previous_page
  current_page - 1 if paginated? && current_page > 1
end

#total_entriesObject



39
40
41
42
43
44
45
# File 'lib/hungry/collection/pagination.rb', line 39

def total_entries
  if paginated?
    pagination['total_entries'].to_i
  else
    response['results'].length
  end
end

#total_pagesObject



47
48
49
50
51
52
53
# File 'lib/hungry/collection/pagination.rb', line 47

def total_pages
  if paginated?
    pagination['total_pages'].to_i
  else
    1
  end
end