Sha256: 38a2a0310643e1af2b4590173e7e97c3290725834320f76b02ffd2eaac9ae71e

Contents?: true

Size: 1.32 KB

Versions: 31

Compression:

Stored size: 1.32 KB

Contents

module Teacup
  module_function

  # Merges two Hashes.  This is similar to `Hash#merge`, except the values will
  # be merged recursively (aka deep merge) when both values for a key are
  # Hashes, and values for the *left* argument are preferred over values on the
  # right.
  #
  # If you pass in a third argument, it will be acted upon directly instead of
  # creating a new Hash.  Usually used with `merge_defaults!`, which merges values
  # from `right` into `left`.
  def merge_defaults(left, right, target={})
    if target != left
      left.each do |key, value|
        if target.has_key? key and value.is_a?(Hash) and target[key].is_a?(Hash)
          target[key] = Teacup::merge_defaults(target[key], value)
        else
          if value.is_a?(Hash)
            # make a copy of the Hash
            value = Teacup::merge_defaults!({}, value)
          end
          target[key] = value
        end
      end
    end

    right.each do |key, value|
      if not target.has_key? key
        target[key] = value
      elsif value.is_a?(Hash) and left[key].is_a?(Hash)
        target[key] = Teacup::merge_defaults(left[key], value, (left==target ? left[key] : {}))
      end
    end
    target
  end

  # modifies left by passing it in as the `target`.
  def merge_defaults!(left, right)
    Teacup::merge_defaults(left, right, left)
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
teacup-2.1.16 lib/teacup/merge_defaults.rb
teacup-2.1.15 lib/teacup/merge_defaults.rb
teacup-2.1.14 lib/teacup/merge_defaults.rb
teacup-2.1.13 lib/teacup/merge_defaults.rb
teacup-2.1.12 lib/teacup/merge_defaults.rb
teacup-2.1.11 lib/teacup/merge_defaults.rb
teacup-2.1.10 lib/teacup/merge_defaults.rb
teacup-2.1.9 lib/teacup/merge_defaults.rb
teacup-2.1.8 lib/teacup/merge_defaults.rb
teacup-2.1.7 lib/teacup/merge_defaults.rb
teacup-2.1.6 lib/teacup/merge_defaults.rb
teacup-2.1.5 lib/teacup/merge_defaults.rb
teacup-2.1.4 lib/teacup/merge_defaults.rb
teacup-2.1.3 lib/teacup/merge_defaults.rb
teacup-2.1.2 lib/teacup/merge_defaults.rb
teacup-2.1.1 lib/teacup/merge_defaults.rb
teacup-2.1.0 lib/teacup/merge_defaults.rb
teacup-2.0.6 lib/teacup/merge_defaults.rb
teacup-2.0.5 lib/teacup/merge_defaults.rb
teacup-2.0.4 lib/teacup/merge_defaults.rb