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.



824
825
826
827
# File 'lib/active_record/refined/ast.rb', line 824

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

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



822
823
824
# File 'lib/active_record/refined/ast.rb', line 822

def key
  @key
end

#operandObject (readonly)

Returns the value of attribute operand.



822
823
824
# File 'lib/active_record/refined/ast.rb', line 822

def operand
  @operand
end

Instance Method Details

#to_arel(table, model) ⇒ Object



829
830
831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/active_record/refined/ast.rb', line 829

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