Class: Lcms::Engine::Pagination

Inherits:
Object
  • Object
show all
Defined in:
app/entities/lcms/engine/pagination.rb

Constant Summary collapse

PARAMS_DEFAULT =
{ page: 1, per_page: 20, order: :asc }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Pagination

Returns a new instance of Pagination.



8
9
10
# File 'app/entities/lcms/engine/pagination.rb', line 8

def initialize(params)
  @params = handle_params params
end

Instance Method Details

#params(strict: false) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'app/entities/lcms/engine/pagination.rb', line 12

def params(strict: false)
  @pagination_params ||= begin
    expected_params = @params.slice(*PARAMS_DEFAULT.keys).symbolize_keys
    pagination = PARAMS_DEFAULT.merge(expected_params)

    pagination[:page] = pagination[:page].to_i
    pagination[:per_page] = pagination[:per_page].to_i
    pagination[:order] = pagination[:order].to_sym

    raise StandardError unless pagination[:page].positive?
    raise StandardError unless pagination[:per_page].positive?
    raise StandardError unless %i(asc desc).include? pagination[:order]

    pagination
  end
  strict ? @pagination_params.slice(:page, :per_page) : @pagination_params
end

#serialize(resources, serializer) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/entities/lcms/engine/pagination.rb', line 30

def serialize(resources, serializer)
  options = {
    adapter: :json,
    each_serializer: serializer,
    meta_key: {
      pagination: {
        total_pages: resources.total_pages,
        current_page: resources.current_page,
        per_page: resources.per_page,
        order: params[:order],
        total_hits: resources.total_entries
      }
    },
    root: :results
  }
  ActiveModelSerializers::SerializableResource.new(resources, options).as_json
end