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.



763
764
765
766
# File 'lib/active_record/refined/ast.rb', line 763

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

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



761
762
763
# File 'lib/active_record/refined/ast.rb', line 761

def key
  @key
end

#operandObject (readonly)

Returns the value of attribute operand.



761
762
763
# File 'lib/active_record/refined/ast.rb', line 761

def operand
  @operand
end

Instance Method Details

#to_arel(table, model) ⇒ Object



768
769
770
771
772
773
774
775
776
777
778
779
780
781
# File 'lib/active_record/refined/ast.rb', line 768

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