Class: ObjectPatch::Operations::Add

Inherits:
Object
  • Object
show all
Defined in:
lib/object_patch/operations/add.rb

Overview

A representation of a JSON pointer add operation.

Instance Method Summary collapse

Constructor Details

#initialize(patch_data) ⇒ void

Setup the add operation with any required arguments.

Options Hash (patch_data):

  • path (String)

    The location in the target document to add.

  • value (Object)

    The value to insert into the target.



36
37
38
39
# File 'lib/object_patch/operations/add.rb', line 36

def initialize(patch_data)
  @path  = patch_data.fetch('path')
  @value = patch_data.fetch('value')
end

Instance Method Details

#apply(target_doc) ⇒ Object

Apply this operation to the provided document and return the updated document. Please note that the changes will be reflected not only in the returned value but the original document that was passed in as well.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/object_patch/operations/add.rb', line 14

def apply(target_doc)
  key = processed_path.last
  inner_obj = ObjectPatch::Pointer.eval(processed_path[0...-1], target_doc)
  
  raise MissingTargetException, @path unless inner_obj

  if key
    ObjectPatch::Operations.add_op(inner_obj, key, @value)
  else
    inner_obj.replace(@value)
  end

  target_doc
end

#processed_pathArray<String>

Returns the path after being expanded by the JSON pointer semantics.



44
45
46
# File 'lib/object_patch/operations/add.rb', line 44

def processed_path
  ObjectPatch::Pointer.parse(@path)
end

#to_patchHash<String => String>

Covert this operation to a format that can be built into a full on JSON patch.



52
53
54
# File 'lib/object_patch/operations/add.rb', line 52

def to_patch
  { 'op' => 'add', 'path' => @path, 'value' => @value }
end