Module: WithScopedQueries::Sort

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/with_scoped_queries/sort.rb

Class Method Summary collapse

Class Method Details

.add_queriable_attributes_to(klass, attributes) ⇒ Object



22
23
24
25
26
# File 'app/models/concerns/with_scoped_queries/sort.rb', line 22

def self.add_queriable_attributes_to(klass, attributes)
  klass.default_sorting_field = attributes.extract_options![:default]
  klass.sorting_fields = attributes
  klass.queriable_attributes.merge!(sort: :sort)
end

.normalize_params(param) ⇒ Object



18
19
20
# File 'app/models/concerns/with_scoped_queries/sort.rb', line 18

def self.normalize_params(param)
  param&.split(/_(?!.*_)/)
end

.query_by(params, scope, klass) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'app/models/concerns/with_scoped_queries/sort.rb', line 8

def self.query_by(params, scope, klass)
  sort_param = params[:sort] || klass.default_sorting_field.to_s
  normalized_params = normalize_params(sort_param)
  if sort_param.present? && klass.sorting_params_allowed?(*normalized_params)
    sort_method_for(klass, scope, *normalized_params)
  else
    scope
  end
end

.sort_method_for(klass, scope, field, direction) ⇒ Object



28
29
30
31
32
33
34
# File 'app/models/concerns/with_scoped_queries/sort.rb', line 28

def self.sort_method_for(klass, scope, field, direction)
  if klass.column_names.include? field
    scope.public_send(:reorder, "#{klass.table_name}.#{field} #{direction}")
  else
    scope.public_send("order_by_#{field}", direction)
  end
end