Class: JSONP3::OpRemove

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

Overview

The JSON Patch remove operation.

Instance Method Summary collapse

Constructor Details

#initialize(pointer) ⇒ OpRemove

Returns a new instance of OpRemove.

Parameters:



74
75
76
77
# File 'lib/json_p3/patch.rb', line 74

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

Instance Method Details

#apply(value, index) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/json_p3/patch.rb', line 83

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

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

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

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

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

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

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

  value
end

#nameObject



79
80
81
# File 'lib/json_p3/patch.rb', line 79

def name
  "remove"
end

#to_hObject



117
118
119
# File 'lib/json_p3/patch.rb', line 117

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