Class: Parse::Constraint::BetweenConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/parse/query/constraints.rb

Overview

A general range constraint that combines greater-than-or-equal and less-than-or-equal constraints for numeric, date/time, and string range queries. This is equivalent to using both $gte and $lte. This constraint works with numbers, dates, times, strings (alphabetical), and any comparable values.

Find products with price between 10 and 50

Product.where(:price.between => [10, 50])

Generates: "price": { "$gte": 10, "$lte": 50 }

Find events between two dates

Event.where(:created_at.between => [start_date, end_date])

Generates: "created_at": { "$gte": start_date, "$lte": end_date }

Find users with age between 18 and 65

User.where(:age.between => [18, 65])

Generates: "age": { "$gte": 18, "$lte": 65 }

Find users with names alphabetically between "Alice" and "John"

User.where(:name.between => ["Alice", "John"])

Generates: "name": { "$gte": "Alice", "$lte": "John" }

A Ruby Range works the same way as a 2-element array. An inclusive

range (..) maps its end to $lte, while an exclusive range (...)

maps its end to $lt.

User.where(:age.between => 18..65)

Generates: "age": { "$gte": 18, "$lte": 65 }

Record.where(:date.between => 5.days.ago...2.days.ago)

Generates: "date": { "$gte": <5 days ago>, "$lt": <2 days ago> }

Beginless/endless ranges only constrain the side that is present.

User.where(:age.between => 18..)

Generates: "age": { "$gte": 18 }

Instance Method Summary collapse

Instance Method Details

#betweenBetweenConstraint

A registered method on a symbol to create the constraint.

Examples:

q.where :field.between => [min_value, max_value]

Returns:



2534
# File 'lib/parse/query/constraints.rb', line 2534

register :between

#buildHash

Returns the compiled constraint.

Returns:

  • (Hash)

    the compiled constraint.



2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
# File 'lib/parse/query/constraints.rb', line 2537

def build
  return build_range(@value) if @value.is_a?(Range)

  value = formatted_value
  unless value.is_a?(Array) && value.length == 2
    raise ArgumentError, "#{self.class}: Value must be an array with exactly 2 elements [min_value, max_value], or a Range"
  end

  min_value, max_value = value

  # Format the values using Parse's formatting (handles dates, numbers, etc.)
  formatted_min = Parse::Constraint.formatted_value(min_value)
  formatted_max = Parse::Constraint.formatted_value(max_value)

  { @operation.operand => {
    Parse::Constraint::GreaterThanOrEqualConstraint.key => formatted_min,
    Parse::Constraint::LessThanOrEqualConstraint.key => formatted_max,
  } }
end