Module: RiceCooker::Sort::ClassMethods

Includes:
Helpers
Defined in:
lib/rice_cooker/sort.rb

Instance Method Summary collapse

Methods included from Helpers

#apply_filter_to_collection, #apply_range_to_collection, #apply_search_to_collection, #apply_sort_to_collection, #check_filtering_param, #check_ranged_param, #check_searching_param, #check_sorting_param, #filterable_fields_for, #format_additional_param, #fuzzy_fields_for, #param_from_defaults, #parse_filtering_param, #parse_ranged_param, #parse_searching_param, #parse_sorting_param, #rangeable_fields_for, #reduce_fields_where, #reduce_where, #searchable_fields_for, #sortable_fields_for

Instance Method Details

#sorted(default_sorting_params = { id: :desc }) ⇒ Object

Will handle collection (index) sorting on inherited resource controllers

All endpoints support multiple sort fields by allowing comma-separated (‘,`) sort fields. Sort fields are applied in the order specified. The sort order for each sort field is ascending unless it is prefixed with a minus (U+002D HYPHEN-MINUS, “-“), in which case it is descending.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rice_cooker/sort.rb', line 20

def sorted(default_sorting_params = { id: :desc })
  cattr_accessor :default_order
  cattr_accessor :sorted_keys

  return unless sorted_keys.nil? || resource_model.nil?

  default_sorting_params = { default_sorting_params => :asc } if default_sorting_params.is_a? Symbol

  # On recupere le default
  self.default_order = default_sorting_params
  self.sorted_keys = (resource_model.respond_to?(:sortable_fields) ? resource_model.sortable_fields : [])
  default_sort = param_from_defaults(default_sorting_params)

  has_scope :sort, default: default_sort, only: [:index] do |controller, scope, value|
    scope = if controller.params[SORT_PARAM].present?
              apply_sort_to_collection(scope, parse_sorting_param(value, resource_model))
            else
              apply_sort_to_collection(scope, default_sorting_params)
            end
    scope
  end

rescue NoMethodError => e
  "Just wanna die ⚓️ #{e}"
  super
end