Class: Parse::Constraint::ArrayNotEmptyConstraint

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

Overview

Array not-empty constraint - shorthand for size > 0. Matches arrays that have at least one element.

q.where :tags.arr_nempty => true   # arrays with 1+ elements
q.where :tags.arr_nempty => false  # arrays with 0 elements (same as empty)

Instance Attribute Summary

Attributes inherited from Parse::Constraint

#operand, #operation, #operator, #value

Instance Method Summary collapse

Methods inherited from Parse::Constraint

#as_json, constraint_keyword, create, formatted_value, #formatted_value, #initialize, #key, #precedence, register, #to_s

Constructor Details

This class inherits a constructor from Parse::Constraint

Instance Method Details

#arr_nemptyArrayNotEmptyConstraint

A registered method on a symbol to create the constraint.

Examples:

q.where :field.arr_nempty => true

Returns:



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

register :arr_nempty

#buildHash

Returns the compiled constraint using aggregation pipeline.

Returns:

  • (Hash)

    the compiled constraint using aggregation pipeline.



664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
# File 'lib/parse/query/constraints.rb', line 664

def build
  value = formatted_value
  unless value == true || value == false
    raise ArgumentError, "#{self.class}: Value must be true or false"
  end

  field_name = Parse::Query.format_field(@operation.operand)
  size_expr = { "$size" => { "$ifNull" => ["$#{field_name}", []] } }

  # If true, match size > 0; if false, match size == 0
  comparison = value ? { "$gt" => [size_expr, 0] } : { "$eq" => [size_expr, 0] }

  pipeline = [
    {
      "$match" => {
        "$expr" => comparison,
      },
    },
  ]

  { "__aggregation_pipeline" => pipeline }
end