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.



628
629
630
631
# File 'lib/active_record/refined/ast.rb', line 628

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

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

#operandObject (readonly)

Returns the value of attribute operand.



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

def operand
  @operand
end

Instance Method Details

#to_arel(table, model) ⇒ Object



633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/active_record/refined/ast.rb', line 633

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