Module: SortableBy::Params

Extended by:
ActiveSupport::Concern
Defined in:
lib/sortable_by/params.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#normalize_sort_value(sort_by, direction) ⇒ Object

Translate the sort_by and direction into a sortable hash



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/sortable_by/params.rb', line 66

def normalize_sort_value(sort_by, direction)
  mapping = self.class.sortable_mapping[sort_by]
  case mapping
  when Symbol
    { mapping => sort_direction }
  when String
    mapping.gsub(':dir', sort_direction.to_s)
  when Array
    mapping.index_with { |_att| direction }
  when Proc
    mapping.call(direction)
  else
    logger.debug("WARNING: Sort attribute '#{sort_by}' is not recognized. Did you mean to pass it to sortable_by?")
    nil
  end
end

#sort_attributeObject

Return the current sort param



46
47
48
# File 'lib/sortable_by/params.rb', line 46

def sort_attribute
  params[:sort].try(:to_sym) || self.class.default_sort_attribute
end

#sort_directionObject

Return the current sort direction

Defaults to :default_sort_dir for all values other than ‘asc’ or ‘desc’



36
37
38
39
40
41
42
# File 'lib/sortable_by/params.rb', line 36

def sort_direction
  if ['asc', 'desc'].include?(params[:dir])
    params[:dir].to_sym
  else
    self.class.default_sort_dir
  end
end

#sortable_queryObject

Return a hash that can be used in an ActiveRecord order query

Example:

MyModel.where(...).order(sortable_query).paginate(...)


55
56
57
58
59
60
61
62
# File 'lib/sortable_by/params.rb', line 55

def sortable_query
  return unless sort_attribute

  normalize_sort_value(
    sort_attribute,
    sort_direction
  )
end