Module: Caprese::Adapter::JsonApi::JsonPointer

Defined in:
lib/caprese/adapter/json_api/json_pointer.rb

Constant Summary collapse

POINTERS =
{
  attribute:    '/data/attributes/%s'.freeze,
  relationship_attribute: '/data/relationships/%s'.freeze,
  relationship_base: '/data/relationships/%s/data'.freeze,
  relationship_primary_data: '/data/relationships/%s/data/%s'.freeze,
  primary_data: '/data/%s'.freeze,
  base: '/data'.freeze
}.freeze

Class Method Summary collapse

Class Method Details

.new(pointer_type, record, value) ⇒ Object

Iterates over the field of an error and converts it to a pointer in JSON API format

Examples:

new(:attribute, record, 'name')
=> '/data/attributes/name'
new(:relationship, record, 'post')
=> '/data/attributes/name'
new(:relationship_attribute, record, 'post.user.name')
=> '/data/relationships/post/data/relationships/user/data/attributes/name'

Parameters:

  • pointer_type (Symbol)

    the type of pointer: :attribute, :relationship, :primary_data

  • the (Record)

    record that owns the errors

  • (Object, Array<Object>)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/caprese/adapter/json_api/json_pointer.rb', line 33

def new(pointer_type, record, value)
  if pointer_type == :relationship_attribute
    values = value.to_s.split('.')
    last_index = values.count - 1

    klass_iteratee = record.class
    values.each_with_index.inject('') do |pointer, (v, i)|
      pointer +
        if ref = (klass_iteratee.reflect_on_association(v) || klass_iteratee.reflect_on_association(klass_iteratee.caprese_unalias_field(v)))
          klass_iteratee = ref.klass

          if i == last_index
            format(POINTERS[:relationship_base], v)
          else
            format(POINTERS[:relationship_attribute], v)
          end
        else
          format(POINTERS[:attribute], v)
        end
    end
  else
    format(POINTERS[pointer_type], *Array.wrap(value))
  end
end