Class: NextPage::Sorter
- Inherits:
-
Object
- Object
- NextPage::Sorter
- Defined in:
- lib/next_page/sorter.rb
Overview
Sorter
Class Sorter reads the sort parameter and applies the related ordering. Results for each parameter string are cached so evaluation only occurs once.
Instance Method Summary collapse
-
#initialize(model) ⇒ Sorter
constructor
Initializes a new sorter.
-
#sort(query, sort_fields) ⇒ Object
Adds sorting to given query based upon the param.
Constructor Details
#initialize(model) ⇒ Sorter
Initializes a new sorter. The given model is used to validate sort attributes as well as build nested sorts.
14 15 16 17 |
# File 'lib/next_page/sorter.rb', line 14 def initialize(model) @model = model @cache = Hash.new { |hash, key| hash[key] = build_sort(key) } end |
Instance Method Details
#sort(query, sort_fields) ⇒ Object
Adds sorting to given query based upon the param. Returns a new query; the existing query is NOT modified.
The query parameter is an ActiveRecord arel or model.
The sort_fields parameter is a string that conforms to the JSON-API specification for sorting fields: jsonapi.org/format/#fetching-sorting
25 26 27 28 29 30 |
# File 'lib/next_page/sorter.rb', line 25 def sort(query, sort_fields) return from_array(query, sort_fields.split(',')) if sort_fields.include?(',') return from_array(query, sort_fields) if sort_fields.is_a? Array apply_sort(query, sort_fields) end |