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

Included in:
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)


463
464
465
466
467
468
469
470
# File 'lib/active_record/refined/ast.rb', line 463

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.



480
481
482
483
484
485
486
487
# File 'lib/active_record/refined/ast.rb', line 480

def dollar_path
  path.inject(+'$') do |so_far, step|
    next so_far << "[#{step}]" if step.is_a?(::Integer)
    name = step.to_s
    so_far << '.' << (name.match?(/\A[[:alpha:]_][[:alnum:]_]*\z/) ?
                      name : %("#{escape_step(step)}"))
  end
end

#escape_step(step) ⇒ Object



489
490
491
# File 'lib/active_record/refined/ast.rb', line 489

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

#steps_arrayObject

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.



474
475
476
# File 'lib/active_record/refined/ast.rb', line 474

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