Module: SnFoil::Rails::ProcessPagination

Extended by:
ActiveSupport::Concern
Defined in:
lib/snfoil/rails/concerns/process_pagination.rb

Instance Method Summary collapse

Instance Method Details

#paginate(**options) ⇒ Object



24
25
26
27
28
29
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 24

def paginate(**options)
  return options[:object] unless options[:object].respond_to?(:page)

  options[:object].page(pagination_page(**options))
                  .per(pagination_per_page(**options))
end

#pagination_count(**options) ⇒ Object



42
43
44
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 42

def pagination_count(**options)
  options[:object].count if options[:object].respond_to? :count
end

#pagination_meta(**options) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 54

def pagination_meta(**options)
  {
    page: pagination_page(**options),
    pages: pagination_pages(**options),
    total: pagination_count(**options),
    per: pagination_per_page(**options)
  }
end

#pagination_page(**options) ⇒ Object



31
32
33
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 31

def pagination_page(**options)
  (options.dig(:request_params, :page) || 1).to_i
end

#pagination_pages(**options) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 46

def pagination_pages(**options)
  count = pagination_count(**options)
  per_page = pagination_per_page(**options)
  return unless count && per_page

  (count.to_f / per_page).ceil.to_i
end

#pagination_per_page(**options) ⇒ Object



35
36
37
38
39
40
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 35

def pagination_per_page(**options)
  per_page_param = (options.dig(:request_params, :per_page) || 10).to_i
  return 1000 if per_page_param.zero? || per_page_param > 1000

  per_page_param
end

#process_pagination(**options) ⇒ Object



63
64
65
66
67
68
# File 'lib/snfoil/rails/concerns/process_pagination.rb', line 63

def process_pagination(**options)
  options[:meta] = pagination_meta(**options)
  options[:object] = paginate(**options)

  options
end