Sha256: be79a7b6b2cfa802b669ee41c1ee7a8e6f3601220b8ade0f3a61dacd3d9d96e5

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

# 
# This module provides methods to diff two hash, patch and unpatch hash
#
module HashDiff

  # Apply patch to object
  #
  # @param [Hash, Array] obj the object to be patchted, can be an Array of a Hash
  # @param [Array] changes e.g. [[ '+', 'a.b', '45' ], [ '-', 'a.c', '5' ], [ '~', 'a.x', '45', '63']]
  #
  # @return the object after patch
  #
  # @since 0.0.1
  def self.patch!(obj, changes)
    changes.each do |change|
      parts = decode_property_path(change[1])
      last_part = parts.last

      parent_node = node(obj, parts[0, parts.size-1])

      if change[0] == '+'
        if last_part.is_a?(Fixnum)
          parent_node.insert(last_part, change[2])
        else
          parent_node[last_part] = change[2]
        end
      elsif change[0] == '-'
        if last_part.is_a?(Fixnum)
          parent_node.delete_at(last_part)
        else
          parent_node.delete(last_part)
        end
      elsif change[0] == '~'
        parent_node[last_part] = change[3]
      end
    end

    obj
  end

  # Unpatch an object
  #
  # @param [Hash, Array] obj the object to be unpatchted, can be an Array of a Hash
  # @param [Array] changes e.g. [[ '+', 'a.b', '45' ], [ '-', 'a.c', '5' ], [ '~', 'a.x', '45', '63']]
  #
  # @return the object after unpatch
  #
  # @since 0.0.1
  def self.unpatch!(obj, changes)
    changes.reverse_each do |change|
      parts = decode_property_path(change[1])
      last_part = parts.last

      parent_node = node(obj, parts[0, parts.size-1])

      if change[0] == '+'
        if last_part.is_a?(Fixnum)
          parent_node.delete_at(last_part)
        else
          parent_node.delete(last_part)
        end
      elsif change[0] == '-'
        if last_part.is_a?(Fixnum)
          parent_node.insert(last_part, change[2])
        else
          parent_node[last_part] = change[2]
        end
      elsif change[0] == '~'
        parent_node[last_part] = change[2]
      end
    end

    obj
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hashdiff-0.0.5 lib/hashdiff/patch.rb
hashdiff-0.0.4 lib/hashdiff/patch.rb