Class: ActiveRecord::Refined::AST::JsonHasKey

Inherits:
Predicate show all
Defined in:
lib/active_record/refined/ast.rb

Overview

Whether a key is in the document. PostgreSQL has an operator for it, ?, which is also what a bind parameter looks like to several drivers; the function it is shorthand for says the same thing and survives.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Predicate

#!, #&, #|

Methods inherited from Node

#as, #asc, #desc

Constructor Details

#initialize(operand, key) ⇒ JsonHasKey

Returns a new instance of JsonHasKey.



624
625
626
627
# File 'lib/active_record/refined/ast.rb', line 624

def initialize(operand, key)
  @operand = operand
  @key = key
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



622
623
624
# File 'lib/active_record/refined/ast.rb', line 622

def key
  @key
end

#operandObject (readonly)

Returns the value of attribute operand.



622
623
624
# File 'lib/active_record/refined/ast.rb', line 622

def operand
  @operand
end

Instance Method Details

#to_arel(table, model) ⇒ Object



629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/active_record/refined/ast.rb', line 629

def to_arel(table, model)
  document = to_arel_operand(operand, table, model)
  name = Arel::Nodes.build_quoted(key.to_s)
  path = Arel::Nodes.build_quoted("$.#{key}")
  case AST.adapter_family(model)
  when :postgresql
    Arel::Nodes::NamedFunction.new('jsonb_exists', [document, name])
  when :mysql
    Arel::Nodes::NamedFunction.new(
      'JSON_CONTAINS_PATH', [document, Arel::Nodes.build_quoted('one'), path])
  else
    Arel::Nodes::NamedFunction.new('json_type', [document, path]).not_eq(nil)
  end
end