Module: Wurk::Api::Pagination
- Defined in:
- app/controllers/wurk/api/pagination.rb
Overview
Pagination helpers shared by every listing endpoint. The contract:
* `?count=` page size (default 25, clamped to 1..200)
* `?page=` 0-indexed page number
* `?substr=` case-insensitive klass/jid filter on the page
Helpers expect an Enumerable that yields whatever JSON-shaped Hash the caller built; substr filtering and slicing happen after serialization so filters work on the same fields the UI reads.
Constant Summary collapse
- DEFAULT_PAGE_SIZE =
25- MAX_PAGE_SIZE =
200
Class Method Summary collapse
- .clamp_float(value, min, max, default) ⇒ Object
- .clamp_int(value, min, max, default) ⇒ Object
- .match?(payload, substr) ⇒ Boolean
-
.slice(enumerable, page) ⇒ Object
Iterates ‘enumerable` and collects up to `count` payloads from the requested page after substr filtering.
- .window(params) ⇒ Object
Class Method Details
.clamp_float(value, min, max, default) ⇒ Object
33 34 35 36 37 |
# File 'app/controllers/wurk/api/pagination.rb', line 33 def clamp_float(value, min, max, default) Float(value).clamp(min, max) rescue ::ArgumentError, ::TypeError default end |
.clamp_int(value, min, max, default) ⇒ Object
27 28 29 30 31 |
# File 'app/controllers/wurk/api/pagination.rb', line 27 def clamp_int(value, min, max, default) Integer(value, 10).clamp(min, max) rescue ::ArgumentError, ::TypeError default end |
.match?(payload, substr) ⇒ Boolean
59 60 61 62 63 64 |
# File 'app/controllers/wurk/api/pagination.rb', line 59 def match?(payload, substr) return true if substr.nil? || substr.empty? needle = substr.downcase payload[:klass].to_s.downcase.include?(needle) || payload[:jid].to_s.downcase.include?(needle) end |
.slice(enumerable, page) ⇒ Object
Iterates ‘enumerable` and collects up to `count` payloads from the requested page after substr filtering. `block` maps each member to a JSON Hash; nil from the block skips the member entirely.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'app/controllers/wurk/api/pagination.rb', line 42 def slice(enumerable, page) results = [] offset = page[:page] * page[:count] idx = 0 enumerable.each do |member| if idx >= offset payload = yield(member) if payload && match?(payload, page[:substr]) results << payload break if results.size >= page[:count] end end idx += 1 end results end |
.window(params) ⇒ Object
19 20 21 22 23 24 25 |
# File 'app/controllers/wurk/api/pagination.rb', line 19 def window(params) { page: [params[:page].to_i, 0].max, count: clamp_int(params[:count], 1, MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE), substr: params[:substr].to_s } end |