Sha256: 0befa6e680390364d95d8a598965cdfa8b1e6f92cdfeaf67c725b3828bd81463

Contents?: true

Size: 1.2 KB

Versions: 49

Compression:

Stored size: 1.2 KB

Contents

module ActiveTools
  module CoreExtension
    
    module DeepMerge
      
      module HashExtension
        # Return the merged Hash with another +hash+, where the possible child hashes are also merged.
        #
        # === Example:
        # 
        #   h1 = {:breakfast => {:eggs => 2, :bread => 1}, :lunch => {:steak => 1, :salad => 1}}
        #   h2 = {:breakfast => {:coffee => :espresso, :juice => 1}, :lunch => {:tea => 2}, :dinner => :none}
        #   h1.deep_merge(h2)
        #   #=> {:breakfast=>{:eggs=>2, :bread=>1, :coffee=>:espresso, :juice=>1}, :lunch=>{:steak=>1, :salad=>1, :tea=>2}, :dinner=>:none}
        def deep_merge(other_hash = {})
          dup.tap do |hash|
            other_hash.each do |key, value|
              if !hash.has_key?(key) || !hash[key].is_a?(Hash)
                hash[key] = value
              elsif hash[key].is_a?(Hash) && value.is_a?(Hash)
                hash[key].deep_merge!(value)
              end
            end
          end
        end

        # .nested_merge replaces the source hash.
        def deep_merge!(other_hash = {})
          replace(deep_merge(other_hash))
        end
      end
      
      ::Hash.send(:include, HashExtension)
      
    end
  end
end

Version data entries

49 entries across 49 versions & 1 rubygems

Version Path
active_tools-0.2.5 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.2.4 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.2.3 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.2.2 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.2.1 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.2.0 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.1.4 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.1.3 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.1.2 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.1.1 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.1.0 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.52 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.51 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.50 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.42 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.41 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.40 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.39 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.38 lib/active_tools/core_extension/deep_merge.rb
active_tools-0.0.37 lib/active_tools/core_extension/deep_merge.rb