Class: JSONP3::Patch::OpAdd

Inherits:
Op
  • Object
show all
Defined in:
lib/json_p3/patch/op_add.rb

Overview

The JSON Patch add operation.

Instance Method Summary collapse

Constructor Details

#initialize(pointer, value) ⇒ OpAdd

Returns a new instance of OpAdd.

Parameters:

  • pointer (JSONPointer)
  • value (JSON-like value)


9
10
11
12
13
# File 'lib/json_p3/patch/op_add.rb', line 9

def initialize(pointer, value)
  super()
  @pointer = pointer
  @value = value
end

Instance Method Details

#apply!(value, index) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/json_p3/patch/op_add.rb', line 19

def apply!(value, index)
  parent, obj = @pointer.resolve_with_parent(value)
  return @value if parent == JSONP3::Pointer::UNDEFINED && @pointer.tokens.empty?

  if parent == JSONP3::Pointer::UNDEFINED
    raise JSONP3::Patch::Error,
          "no such property or item '#{@pointer.parent}' (#{name}:#{index})"
  end

  target = @pointer.tokens.last
  if parent.is_a?(Array)
    if obj == JSONP3::Pointer::UNDEFINED
      raise JSONP3::Patch::Error, "index out of range (#{name}:#{index})" unless target == "-"

      parent << @value
    else
      parent.insert(target.to_i, @value)
    end
  elsif parent.is_a?(Hash)
    parent[target] = @value
  else
    raise JSONP3::Patch::Error, "unexpected operation on #{parent.class} (#{name}:#{index})"
  end

  value
end

#nameObject



15
16
17
# File 'lib/json_p3/patch/op_add.rb', line 15

def name
  "add"
end

#to_hObject



46
47
48
# File 'lib/json_p3/patch/op_add.rb', line 46

def to_h
  { "op" => name, "path" => @pointer.to_s, "value" => @value }
end