Method: Magiq::Query.sort

Defined in:
lib/magiq/query.rb

.sort(fields) ⇒ Object



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/magiq/query.rb', line 122

def self.sort(fields)
  param :sort, type: :string, array: :always, limit: fields.size
  apply :sort do |raw_vals|
    vals = raw_vals.is_a?(Array) ? raw_vals : raw_vals.split(',')

    vals.reduce(scope) do |scope, val|
      col = if val.start_with?('-')
        direction = :desc
        val.sub('-', '').to_sym
      elsif val.start_with?('+')
        direction = :asc
        val.sub('+', '').to_sym
      else
        bad! "A sort order was not specified for the sort field value " \
        "'#{val}', it must be prefixed with either a plus (+#{val}) for " \
        "ascending order, or a minus (-#{val}) for decending order"
      end

      unless fields.include?(col)
        bad! "A provided sorting field: #{col}, is unknown or unsortable. The " \
        "permitted values are: #{fields.join(', ')}"
      end

      if is_unqualified?(col)
        scope.order("\"#{col}\" #{direction}")
      else
        scope.order(col => direction)
      end
    end
  end
end