Class: HashDiff

Inherits:
Object
  • Object
show all
Defined in:
lib/patch_utils/hash_diff.rb

Overview

Get diff from two hashes. (or from other data structure) return format: {:from => , :to => }

HashDiff.get_diff 1, 1 # => nil HashDiff.get_diff 1, 2 # => :to=>2 HashDiff.get_diff(=> 1, :b => 2, :c => ‘4’, => 4, :b => true, :c => 5) do |x, y| x.is_a?(Fixnum) || y.is_a?(TrueClass) end # => :from=>{:c=>“4”, :to=>:c=>5} HashDiff.get_diff [1,2,3], # => href="2,3">from=>, :to=> a = :same_num=>0, :an_other_num=>3, :create=>{:user=>[“new”, “save”], :an_array=>[1, 2, 3], :complex_json=>:f=>“x”}}} b = :same_num=>0, :update=>{:user=>[“edit”, “update”], :an_array=>[1, 2, 4], :an_other_array=>, :complex_json=>:f=>“g”, :h=>“i”}}} HashDiff.get_diff a, b # => :an_other_num=>3, :create=>{:user=>[“new”, “save”], :an_array=>, :complex_json=>:a=>{:b=>{:f=>“x”}}}, :to=>:update=>{:user=>[“edit”, “update”], :an_array=>, :an_other_array=>, :complex_json=>:a=>{:b=>{:f=>“g”, :h=>“i”}}}}

Class Method Summary collapse

Class Method Details

.get_diff(h1, h2, &blk) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/patch_utils/hash_diff.rb', line 16

def self.get_diff h1, h2, &blk
  if block_given?
    return nil if yield(h1, h2)
  else
    return nil if h1 == h2
  end

  if h1.is_a?(Array) && h2.is_a?(Array)
    return {:from => (h1 - h2), :to => (h2 - h1)}
  end

  if h1.is_a?(Hash) && h2.is_a?(Hash)
    all_keys = (h1.keys | h2.keys)
    from = h1.clone
    to = h2.clone
    all_keys.each do |k|
      if h1.keys.include?(k) && h2.keys.include?(k)
        if block_given?
          if yield(h1[k], h2[k])
            from.delete(k)
            to.delete(k)
          end
        else
          if h1[k] == h2[k]
            from.delete(k)
            to.delete(k)
          end
        end
        _diff = self.get_diff(h1[k], h2[k], &blk)
        if _diff.present?
          from[k] = _diff[:from]
          to[k] = _diff[:to]
        end
      end
    end
    return {:from => from, :to => to}
  end
  {:from => h1, :to => h2}
end