Module: RelationBuilder::ExtDeepMerge

Defined in:
lib/relation_builder/ext_deep_merge.rb

Instance Method Summary collapse

Instance Method Details

#ext_deep_merge(other_hash, &block) ⇒ Object

Alternative for native method of Hash It call block for any coincide keys even if values is Hash too



5
6
7
8
9
# File 'lib/relation_builder/ext_deep_merge.rb', line 5

def ext_deep_merge(other_hash, &block)
  ext_hash = dup
  ext_hash.send(:extend, RelationBuilder::ExtDeepMerge) unless ext_hash.is_a? RelationBuilder::ExtDeepMerge
  ext_hash.ext_deep_merge!(other_hash, &block)
end

#ext_deep_merge!(other_hash, &block) ⇒ Object

Same as ext_deep_merge, but modifies self.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/relation_builder/ext_deep_merge.rb', line 12

def ext_deep_merge!(other_hash, &block)
  other_hash.each_pair do |current_key, other_value|
    this_value = self[current_key]
    self[current_key] =
        if block_given? && key?(current_key)
          block.call(current_key, this_value, other_value)
        else
          if this_value.is_a?(Hash) && other_value.is_a?(Hash)
            this_value.ext_deep_merge(other_value, &block)
          else
            other_value
          end
        end
  end
  self
end