Class: JSONP3::OpMove

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

Overview

The JSON Patch move operation.

Instance Method Summary collapse

Constructor Details

#initialize(from, pointer) ⇒ OpMove

Returns a new instance of OpMove.

Parameters:



175
176
177
178
179
# File 'lib/json_p3/patch.rb', line 175

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

Instance Method Details

#apply(value, index) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/json_p3/patch.rb', line 185

def apply(value, index)
  if @pointer.relative_to?(@from)
    raise JSONPatchError,
          "can't move object to one of its children (#{name}:#{index})"
  end

  # Grab the source value.
  source_parent, source_obj = @from.resolve_with_parent(value)
  if source_obj == JSONP3::JSONPointer::UNDEFINED
    raise JSONPatchError,
          "source object does not exist (#{name}:#{index})"
  end

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

  # Delete the target value from the source location.
  if source_parent.is_a?(Array)
    source_parent.delete_at(source_target.to_i)
  elsif source_parent.is_a?(Hash)
    source_parent.delete(source_target)
  end

  # Find the parent of the destination pointer.
  dest_parent, _dest_obj = @pointer.resolve_with_parent(value)
  return source_obj if dest_parent == JSONP3::JSONPointer::UNDEFINED

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

  # Write the source value to the destination.
  if dest_parent.is_a?(Array)
    if dest_target == "-"
      dest_parent << source_obj
    else
      dest_parent[dest_target.to_i] = source_obj
    end
  elsif dest_parent.is_a?(Hash)
    dest_parent[dest_target] = source_obj
  end

  value
end

#nameObject



181
182
183
# File 'lib/json_p3/patch.rb', line 181

def name
  "move"
end

#to_hObject



235
236
237
# File 'lib/json_p3/patch.rb', line 235

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