Module: ActiveRecord::Refined::AST::JsonSteps

Included in:
JsonExcept, JsonPath, JsonSet
Defined in:
lib/active_record/refined/ast.rb

Overview

A path into a JSON document, spelled the two ways the adapters want it. Shared, because reading a value and setting one walk the same path.

Instance Method Summary collapse

Instance Method Details

#check_steps(path, called) ⇒ Object

Raises:

  • (ArgumentError)


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

def check_steps(path, called)
  raise ArgumentError, "#{called} needs a key or an index" if path.empty?
  path.each do |step|
    next if step.is_a?(::Integer) || step.is_a?(::String) || step.is_a?(::Symbol)
    raise ArgumentError, "a step is a key or an array index, not #{step.inspect}"
  end
  path
end

#dollar_pathObject

MySQL and SQLite take a path expression instead, where an integer is a subscript and a name that is not plain has to be quoted.



645
646
647
# File 'lib/active_record/refined/ast.rb', line 645

def dollar_path
  path.inject(+"$") { |so_far, step| so_far << dollar_step(step) }
end

#dollar_step(step) ⇒ Object



649
650
651
652
653
654
# File 'lib/active_record/refined/ast.rb', line 649

def dollar_step(step)
  return "[#{step}]" if step.is_a?(::Integer)
  name = step.to_s
  "." + (name.match?(/\A[[:alpha:]_][[:alnum:]_]*\z/) ?
         name : %("#{escape_step(step)}"))
end

#escape_step(step) ⇒ Object



656
657
658
# File 'lib/active_record/refined/ast.rb', line 656

def escape_step(step)
  step.to_s.gsub("\\", "\\\\").gsub('"', '\\"')
end

#steps_array(steps = path) ⇒ Object

PostgreSQL takes the steps as a text array, where every element is quoted so that a comma or a brace in a key is part of it. except writes its keys the same way, which are steps of no one path.



639
640
641
# File 'lib/active_record/refined/ast.rb', line 639

def steps_array(steps = path)
  "{#{steps.map { |step| %("#{escape_step(step)}") }.join(',')}}"
end