Module: Philiprehberger::JsonMerge::MergePatch

Defined in:
lib/philiprehberger/json_merge/merge_patch.rb

Overview

RFC 7396 JSON Merge Patch implementation

Recursively merges a patch into a target document. Hash values are deep merged, nil values remove keys.

Class Method Summary collapse

Class Method Details

.call(target, patch) ⇒ Hash, Object

Apply a merge patch to a target document

Parameters:

  • target (Hash, Object)

    the target document

  • patch (Hash, Object)

    the merge patch to apply

Returns:

  • (Hash, Object)

    the patched document



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/philiprehberger/json_merge/merge_patch.rb', line 15

def self.call(target, patch)
  return patch unless patch.is_a?(Hash)

  result = target.is_a?(Hash) ? target.dup : {}

  patch.each do |key, value|
    if value.nil?
      result.delete(key)
    elsif value.is_a?(Hash)
      existing = result[key]
      result[key] = call(existing.is_a?(Hash) ? existing : {}, value)
    else
      result[key] = value
    end
  end

  result
end

.generate(source, target) ⇒ Hash?

Generate a merge patch that transforms source into target

Parameters:

  • source (Hash, Object)

    the source document

  • target (Hash, Object)

    the target document

Returns:

  • (Hash, nil)

    the merge patch, or nil if documents are equal



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
# File 'lib/philiprehberger/json_merge/merge_patch.rb', line 39

def self.generate(source, target)
  return target unless source.is_a?(Hash) && target.is_a?(Hash)

  patch = {}

  # Keys removed or changed in target
  source.each do |key, value|
    if target.key?(key)
      if value.is_a?(Hash) && target[key].is_a?(Hash)
        sub_patch = generate(value, target[key])
        patch[key] = sub_patch unless sub_patch.nil? || (sub_patch.is_a?(Hash) && sub_patch.empty?)
      elsif value != target[key]
        patch[key] = target[key]
      end
    else
      patch[key] = nil
    end
  end

  # Keys added in target
  target.each do |key, value|
    patch[key] = value unless source.key?(key)
  end

  patch.empty? ? {} : patch
end