Class: JSONP3::Patch::OpMove

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

Overview

The JSON Patch move operation.

Instance Method Summary collapse

Constructor Details

#initialize(from, pointer) ⇒ OpMove

Returns a new instance of OpMove.

Parameters:

  • from (JSONPointer)
  • pointer (JSONPointer)


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

def initialize(from, pointer)
  super()
  @from = from
  @pointer = pointer
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/json_p3/patch/op_move.rb', line 19

def apply!(value, index)
  if @pointer.relative_to?(@from)
    raise JSONP3::Patch::Error,
          "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::Pointer::UNDEFINED
    raise JSONP3::Patch::Error,
          "source object does not exist (#{name}:#{index})"
  end

  source_target = @from.tokens.last
  if source_target == JSONP3::Pointer::UNDEFINED
    raise JSONP3::Patch::Error,
          "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::Pointer::UNDEFINED

  dest_target = @pointer.tokens.last
  if dest_target == JSONP3::Pointer::UNDEFINED
    raise JSONP3::Patch::Error,
          "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



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

def name
  "move"
end

#to_hObject



69
70
71
# File 'lib/json_p3/patch/op_move.rb', line 69

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