forked from G5/active_model_serializers_contrib
/
pagination_serializer.rb
36 lines (28 loc) · 1.11 KB
/
pagination_serializer.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class ActiveModel::PaginationSerializer < ActiveModel::ArraySerializer
def initialize_with_pagination(object, opts={})
per_page = object.limit_value
offset = object.offset_value
current_page = offset ? (offset / per_page) + 1 : 1
total_items = item_count(object)
total_pages = per_page ? (total_items / per_page.to_f).ceil : 1
prev_page = current_page - 1
prev_page = nil if prev_page < 1
next_page = current_page + 1
next_page = nil if next_page > total_pages
opts[:meta] ||= {}
opts[:meta][:current_page] = current_page
opts[:meta][:total_pages] = total_pages
opts[:meta][:total_items] = total_items
opts[:meta][:prev_page] = prev_page
opts[:meta][:next_page] = next_page
opts[:meta][:per_page] = per_page
initialize_without_pagination(object, opts)
end
alias_method :initialize_without_pagination, :initialize
alias_method :initialize, :initialize_with_pagination
private
def item_count(object)
initial_count = object.limit(nil).offset(nil).count(:all)
(initial_count.respond_to? :count) ? initial_count.count : initial_count
end
end