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

#between ⇒ BetweenConstraint

A registered method on a symbol to create the constraint.

Examples:

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

Returns:



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

register :between

#build ⇒ Hash

Returns the compiled constraint.

Returns:

  • (Hash) —

    the compiled constraint.



3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
# File 'lib/parse/query/constraints.rb', line 3270

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