Class: ActiveRecord::Refined::AST::JsonPath

Inherits:
Node
  • Object
show all
Includes:
Arithmetics, JsonComparable, JsonDocument, JsonSteps, Predications
Defined in:
lib/active_record/refined/ast.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from JsonComparable

#between?, #in?, #not_between?, #not_in?

Methods included from JsonSteps

#check_steps, #dollar_path, #dollar_step, #escape_step, #steps_array

Methods included from Arithmetics

#&, #*, #+, #-, #/, #<<, #>>, #^, #|, #~

Methods included from Predications

#!=, #!~, #<, #<=, #==, #=~, #>, #>=, #between?, #bury, #casecmp?, #contains?, #dig, #dig_json, #distinct_from?, #end_with?, #except, #false?, #ilike?, #in?, #include?, #intersect?, #key?, #like?, #member?, #not_between?, #not_distinct_from?, #not_false?, #not_ilike?, #not_in?, #not_like?, #not_null?, #not_true?, #null?, #start_with?, #subset?, #superset?, #true?, #when

Methods inherited from Node

#as, #asc, #desc

Constructor Details

#initialize(operand, path, as_json: false) ⇒ JsonPath

Returns a new instance of JsonPath.



598
599
600
601
602
# File 'lib/active_record/refined/ast.rb', line 598

def initialize(operand, path, as_json: false)
  @operand = operand
  @path = check_steps(path, 'dig')
  @as_json = as_json
end

Instance Attribute Details

#as_jsonObject (readonly)

Returns the value of attribute as_json.



596
597
598
# File 'lib/active_record/refined/ast.rb', line 596

def as_json
  @as_json
end

#operandObject (readonly)

Returns the value of attribute operand.



596
597
598
# File 'lib/active_record/refined/ast.rb', line 596

def operand
  @operand
end

#pathObject (readonly)

Returns the value of attribute path.



596
597
598
# File 'lib/active_record/refined/ast.rb', line 596

def path
  @path
end

Instance Method Details

#to_arel(table, model) ⇒ Object



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/active_record/refined/ast.rb', line 604

def to_arel(table, model)
  document = to_arel_operand(operand, table, model)
  case AST.adapter_family(model)
  when :postgresql
    Arel::Nodes::InfixOperation.new(
      as_json ? :"#>" : :"#>>", document, Arel::Nodes.build_quoted(steps_array))
  when :mysql
    extracted = Arel::Nodes::NamedFunction.new(
      'JSON_EXTRACT', [document, Arel::Nodes.build_quoted(dollar_path)])
    as_json ? extracted : Arel::Nodes::NamedFunction.new('JSON_UNQUOTE', [extracted])
  else
    extracted = Arel::Nodes::InfixOperation.new(
      as_json ? :"->" : :"->>", document, Arel::Nodes.build_quoted(dollar_path))
    # SQLite's ->> gives back the value with its type, where the other
    # two give text.  Cast so that `dig(:n) == '5'` means the same
    # thing everywhere, and a number wants a cast everywhere too.
    as_json ? extracted : Arel::Nodes::NamedFunction.new(
      'CAST', [Arel::Nodes::As.new(extracted, Arel::Nodes::SqlLiteral.new('text'))])
  end
end