Class: TentD::JsonPatch

Inherits:
Object
  • Object
show all
Defined in:
lib/tentd/json_patch.rb

Defined Under Namespace

Classes: Error, HashPointer, ObjectExists, ObjectNotFound

Constant Summary collapse

OPERATIONS =
%w( add remove replace move copy test )

Class Method Summary collapse

Class Method Details

.add(object, patch_object) ⇒ Object



132
133
134
135
136
137
138
139
140
141
# File 'lib/tentd/json_patch.rb', line 132

def add(object, patch_object)
  pointer = HashPointer.new(object, patch_object["add"])
  if pointer.exists?
    raise ObjectExists unless pointer.value_class == Array
  end
  pointer.value = patch_object["value"]
  object
rescue HashPointer::InvalidPointer => e
  raise ObjectExists
end

.copy(object, patch_object) ⇒ Object



167
168
169
170
171
172
# File 'lib/tentd/json_patch.rb', line 167

def copy(object, patch_object)
  from_pointer = HashPointer.new(object, patch_object["copy"])
  add(object, { "add" => patch_object["to"], "value" => from_pointer.value })
rescue HashPointer::InvalidPointer => e
  raise ObjectNotFound
end

.merge(object, patch) ⇒ Object



124
125
126
127
128
129
130
# File 'lib/tentd/json_patch.rb', line 124

def merge(object, patch)
  patch.each do |patch_object|
    operation = OPERATIONS.find { |key| !patch_object[key].nil? }
    send(operation, object, patch_object)
  end
  object
end

.move(object, patch_object) ⇒ Object



160
161
162
163
164
165
# File 'lib/tentd/json_patch.rb', line 160

def move(object, patch_object)
  pointer = HashPointer.new(object, patch_object["move"])
  pointer.move_to patch_object["to"]
rescue HashPointer::InvalidPointer => e
  raise ObjectNotFound
end

.remove(object, patch_object) ⇒ Object



143
144
145
146
147
148
149
# File 'lib/tentd/json_patch.rb', line 143

def remove(object, patch_object)
  pointer = HashPointer.new(object, patch_object["remove"])
  pointer.delete
  object
rescue HashPointer::InvalidPointer => e
  raise ObjectNotFound
end

.replace(object, patch_object) ⇒ Object



151
152
153
154
155
156
157
158
# File 'lib/tentd/json_patch.rb', line 151

def replace(object, patch_object)
  pointer = HashPointer.new(object, patch_object["replace"])
  pointer.delete
  pointer.value = patch_object["value"]
  object
rescue HashPointer::InvalidPointer => e
  raise ObjectNotFound
end

.test(object, patch_object) ⇒ Object

Raises:



174
175
176
177
178
# File 'lib/tentd/json_patch.rb', line 174

def test(object, patch_object)
  pointer = HashPointer.new(object, patch_object["test"])
  raise ObjectNotFound unless pointer.exists?
  raise ObjectNotFound unless pointer.value == patch_object["value"]
end