Module: Dscf::Core::Pagination
- Extended by:
- ActiveSupport::Concern
- Included in:
- Common
- Defined in:
- app/controllers/concerns/dscf/core/pagination.rb
Instance Method Summary collapse
- #default_per_page ⇒ Object
- #order_by ⇒ Object
- #order_direction ⇒ Object
- #page_no ⇒ Object
- #paginate ⇒ Object
- #paginate_offset ⇒ Object
-
#pagination_links(total_pages) ⇒ Object
Generate HATEOAS pagination links.
- #per_page ⇒ Object
Instance Method Details
#default_per_page ⇒ Object
6 7 8 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 6 def default_per_page 10 end |
#order_by ⇒ Object
22 23 24 25 26 27 28 29 30 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 22 def order_by allowed_columns = if respond_to?(:allowed_order_columns, true) allowed_order_columns else %w[id created_at updated_at] end requested_column = params.fetch(:order_by, "id").to_s allowed_columns.include?(requested_column) ? requested_column : "id" end |
#order_direction ⇒ Object
32 33 34 35 36 37 38 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 32 def order_direction if %w[asc desc].include?(params.fetch(:order_direction, "asc").to_s.downcase) params.fetch(:order_direction, "asc").to_s.downcase else "asc" end end |
#page_no ⇒ Object
10 11 12 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 10 def page_no params[:page]&.to_i || 1 end |
#paginate ⇒ Object
40 41 42 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 40 def paginate ->(it) { it.limit(per_page).offset(paginate_offset).order("#{order_by}": order_direction) } end |
#paginate_offset ⇒ Object
18 19 20 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 18 def paginate_offset (page_no - 1) * per_page end |
#pagination_links(total_pages) ⇒ Object
Generate HATEOAS pagination links
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 45 def pagination_links(total_pages) base_path = request.path current_params = request.query_parameters.except("page") links = {} links[:first] = build_page_url(base_path, current_params, 1) links[:prev] = (build_page_url(base_path, current_params, page_no - 1) if page_no > 1) links[:next] = (build_page_url(base_path, current_params, page_no + 1) if page_no < total_pages) links[:last] = build_page_url(base_path, current_params, total_pages) links end |
#per_page ⇒ Object
14 15 16 |
# File 'app/controllers/concerns/dscf/core/pagination.rb', line 14 def per_page params[:per_page]&.to_i || default_per_page end |