Class: ObjectPatch::Operations::Copy

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

Overview

A representation of a JSON pointer copy operation.

Instance Method Summary collapse

Constructor Details

#initialize(patch_data) ⇒ void

Setup the replace operation with any required arguments.

Parameters:

  • patch_data (Hash)

    Parameters necessary to build the operation.

Options Hash (patch_data):

  • path (String)

    The location in the target document to duplicate the data to.

  • from (String)

    The source data that will be copied into the new location.



41
42
43
44
# File 'lib/object_patch/operations/copy.rb', line 41

def initialize(patch_data)
  @from = patch_data.fetch('from')
  @path = patch_data.fetch('path')
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.

Parameters:

  • target_doc (Object)

    The document that will be modified by this patch.

Returns:

  • (Object)

    The modified document



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

def apply(target_doc)
  src_key = processed_from.last
  dst_key = processed_path.last

  src_obj = ObjectPatch::Pointer.eval(processed_from[0...-1], target_doc)
  dst_obj = ObjectPatch::Pointer.eval(processed_path[0...-1], target_doc)

  if src_obj.is_a?(Array)
    raise ObjectPatch::InvalidIndexError unless src_key =~ /\A\d+\Z/
    copied_obj = src_obj.fetch(src_key.to_i)
  else
    copied_obj = src_obj.fetch(src_key)
  end

  ObjectPatch::Operations.add_op(dst_obj, dst_key, copied_obj)

  target_doc
end

#processed_fromArray<String>

Returns the from field after being expanded by the JSON pointer semantics.

Returns:

  • (Array<String>)

    Expanded pointer path



49
50
51
# File 'lib/object_patch/operations/copy.rb', line 49

def processed_from
  ObjectPatch::Pointer.parse(@from)
end

#processed_pathArray<String>

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

Returns:

  • (Array<String>)

    Expanded pointer path



56
57
58
# File 'lib/object_patch/operations/copy.rb', line 56

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.

Returns:

  • (Hash<String => String>)

    JSON patch copy operation



64
65
66
# File 'lib/object_patch/operations/copy.rb', line 64

def to_patch
  { 'op' => 'copy', 'from' => @from, 'path' => @path }
end