Method: Magiq::Query.range

Defined in:
lib/magiq/query.rb

.range(field, opts = {}) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/magiq/query.rb', line 182

def self.range(field, opts = {})
  lt_param  = :"#{field}_lt"
  lte_param = :"#{field}_lte"
  gt_param  = :"#{field}_gt"
  gte_param = :"#{field}_gte"
  eq_param  = field.to_sym

  param(lt_param,  type: opts[:type] || :whole)
  param(lte_param, type: opts[:type] || :whole)
  param(gt_param,  type: opts[:type] || :whole)
  param(gte_param, type: opts[:type] || :whole)
  param(eq_param,  type: opts[:type] || :whole)

  exclusive(gt_param, gte_param)
  exclusive(lt_param, lte_param)
  mutual(eq_param, exclusive: [lt_param, lte_param, gt_param, gte_param])

  check do
    next if Magiq::Utils.present?(params[eq_param])

    lt_par = if (lt_val = params[lte_param])
      lte_param
    elsif (lt_val = params[lt_param])
      lt_param
    end

    gt_par = if (gt_val = params[gte_param])
      gte_param
    elsif (gt_val = params[gt_param])
      gt_param
    end

    next unless lt_par && gt_par

    if lt_val > gt_val
      bad! "A value of #{lt_val} was provided for `#{lt_par}` but a value " \
      "of #{gt_val} was provided for `#{gt_par}`. The permitted value of  " \
      "`#{lt_par}` must be less than the permitted value provided for " \
      "`#{gt_par}`."
    end

    if lt_val == gt_val
      bad! "The same value of #{gt_val} was provided for both `#{lt_par}` " \
      "and #{gt_par}. The permitted value of `#{lt_par}` must be " \
      "less than the permitted value provided for `#{gt_par}`."
    end
  end

  apply(eq_param) do |val|
    if is_unqualified?(field)
      scope.where("#{field} = ?", val)
    else
      scope.where(model.arel_table[field].eq(val))
    end
  end

  apply(gt_param) do |val|
    if is_unqualified?(field)
      scope.where("#{field} > ?", val)
    else
      scope.where(model.arel_table[field].gt(val))
    end
  end

  apply(lt_param) do |val|
    if is_unqualified?(field)
      scope.where("#{field} < ?", val)
    else
      scope.where(model.arel_table[field].lt(val))
    end
  end

  apply(gte_param) do |val|
    if is_unqualified?(field)
      scope.where("#{field} >= ?", val)
    else
      scope.where(model.arel_table[field].gte(val))
    end
  end

  apply(lte_param) do |val|
    if is_unqualified?
      scope.where("#{field} <= ?", val)
    else
      scope.where(model.arel_table[field].lte(val))
    end
  end
end