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)


475
476
477
478
479
480
481
482
# File 'lib/active_record/refined/ast.rb', line 475

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.



493
494
495
# File 'lib/active_record/refined/ast.rb', line 493

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

#dollar_step(step) ⇒ Object



497
498
499
500
501
502
# File 'lib/active_record/refined/ast.rb', line 497

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



504
505
506
# File 'lib/active_record/refined/ast.rb', line 504

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.



487
488
489
# File 'lib/active_record/refined/ast.rb', line 487

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