class ApiMe::Sorting

Attributes

custom_sort_options[RW]
scope[RW]
sort_criteria[RW]
sort_reverse[RW]

Public Class Methods

new(scope:, sort_params:, custom_sort_options: {}) click to toggle source
# File lib/api_me/sorting.rb, line 7
def initialize(scope:, sort_params:, custom_sort_options: {})
  self.scope = scope

  return unless sort_params

  self.sort_criteria = sort_params[:criteria] || default_sort_criteria
  self.sort_reverse = sort_params[:reverse] || false
  self.custom_sort_options = custom_sort_options
end

Public Instance Methods

results() click to toggle source
# File lib/api_me/sorting.rb, line 17
def results
  sorting? ? sort(sort_criteria).scope : scope
end
sort_meta() click to toggle source
# File lib/api_me/sorting.rb, line 21
def sort_meta
  return {} unless sorting?
  {
    criteria: sort_meta_criteria,
    reverse: sort_reverse
  }
end

Protected Instance Methods

sort(criteria = default_sort_criteria) click to toggle source
# File lib/api_me/sorting.rb, line 39
def sort(criteria = default_sort_criteria)
  self.scope = sorted_scope(criteria)
  self
end
sort_meta_criteria() click to toggle source
# File lib/api_me/sorting.rb, line 31
def sort_meta_criteria
  if sort_criteria.blank?
    default_sort_criteria
  else
    sort_criteria
  end
end
sorted_scope(criteria) click to toggle source
# File lib/api_me/sorting.rb, line 44
def sorted_scope(criteria)
  criteria_key = criteria.to_sym
  if custom_sort_options.key?(criteria_key)
    if sort_reverse == 'true'
      custom_sort_scope(criteria_key).order(Arel.sql("#{custom_sort_options[criteria_key][:column]} DESC"))
    else
      custom_sort_scope(criteria_key).order(Arel.sql("#{custom_sort_options[criteria_key][:column]} ASC"))
    end
  elsif sort_reverse == 'true'
    scope.order(criteria => :desc)
  else
    scope.order(criteria => :asc)
  end
end

Private Instance Methods

custom_sort_scope(criteria) click to toggle source
# File lib/api_me/sorting.rb, line 61
def custom_sort_scope(criteria)
  custom_sort_options[criteria].key?(:joins) ? scope.joins(custom_sort_options[criteria][:joins]) : scope
end
default_sort_criteria() click to toggle source
# File lib/api_me/sorting.rb, line 65
def default_sort_criteria
  'id'
end
sorting?() click to toggle source
# File lib/api_me/sorting.rb, line 69
def sorting?
  sort_criteria || sort_reverse
end