class BMC::Sorter include BMC::SortingHelper attr_reader :collection, :sort_param, :column, :direction def initialize(collection, sort_param = nil) @collection = collection @sort_param = sort_param @column, @direction = sortable_column_order(sort_param.to_s) end def sort raise NotImplementedError end def call # Don't replace by `collection.reorder(sort)` # #sort can change #collection and must be called before #collection order = sort collection.reorder(order) end def self.call(...) new(...).call end private def inverted_direction {asc: :desc, desc: :asc}[direction] end def joins(...) @collection = @collection.joins(...) end def left_joins(...) @collection = @collection.left_joins(...) end def by_column(c = column) {c => direction} end def by_lower(c = column) Arel.sql "LOWER(#{c}) #{direction}" end end