Class: JSONP3::Patch::OpRemove

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

Overview

The JSON Patch remove operation.

Instance Method Summary collapse

Constructor Details

#initialize(pointer) ⇒ OpRemove

Returns a new instance of OpRemove.

Parameters:

  • pointer (JSONPointer)


8
9
10
11
# File 'lib/json_p3/patch/op_remove.rb', line 8

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

Instance Method Details

#apply!(value, index) ⇒ Object



17
18
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
45
46
47
48
49
# File 'lib/json_p3/patch/op_remove.rb', line 17

def apply!(value, index)
  parent, obj = @pointer.resolve_with_parent(value)

  if parent == JSONP3::Pointer::UNDEFINED && @pointer.tokens.empty?
    raise JSONP3::Patch::Error,
          "can't remove root (#{name}:#{index})"
  end

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

  target = @pointer.tokens.last
  if target == JSONP3::Pointer::UNDEFINED
    raise JSONP3::Patch::Error,
          "unexpected operation (#{name}:#{index})"
  end

  if parent.is_a?(Array)
    raise JSONP3::Patch::Error, "no item to remove (#{name}:#{index})" if obj == JSONP3::Pointer::UNDEFINED

    parent.delete_at(target.to_i)
  elsif parent.is_a?(Hash)
    raise JSONP3::Patch::Error, "no property to remove (#{name}:#{index})" if obj == JSONP3::Pointer::UNDEFINED

    parent.delete(target)
  else
    raise JSONP3::Patch::Error, "unexpected operation on #{parent.class} (#{name}:#{index})"
  end

  value
end

#nameObject



13
14
15
# File 'lib/json_p3/patch/op_remove.rb', line 13

def name
  "remove"
end

#to_hObject



51
52
53
# File 'lib/json_p3/patch/op_remove.rb', line 51

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