Sha256: e59c250a2d82672be1774fbb1870e75577af330343f2cf4d017ef094d4733604

Contents?: true

Size: 1.45 KB

Versions: 21

Compression:

Stored size: 1.45 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
        if value.is_a?(Hash)
          # make a copy of the Hash
          value = Teacup::merge_defaults!({}, value)
        end
        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

21 entries across 21 versions & 1 rubygems

Version Path
teacup-1.2.5 lib/teacup/merge_defaults.rb
teacup-1.2.4 lib/teacup/merge_defaults.rb
teacup-1.2.3 lib/teacup/merge_defaults.rb
teacup-1.2.2 lib/teacup/merge_defaults.rb
teacup-1.0.4 lib/teacup/merge_defaults.rb
teacup-1.0.3 lib/teacup/merge_defaults.rb
teacup-1.0.2 lib/teacup/merge_defaults.rb
teacup-1.0.1 lib/teacup/merge_defaults.rb
teacup-1.0.0 lib/teacup/merge_defaults.rb
teacup-0.3.12 lib/teacup/merge_defaults.rb
teacup-0.3.11 lib/teacup/merge_defaults.rb
teacup-0.3.10 lib/teacup/merge_defaults.rb
teacup-0.3.9 lib/teacup/merge_defaults.rb
teacup-0.3.8 lib/teacup/merge_defaults.rb
teacup-0.3.7 lib/teacup/merge_defaults.rb
teacup-0.3.6 lib/teacup/merge_defaults.rb
teacup-0.3.5 lib/teacup/merge_defaults.rb
teacup-0.3.4 lib/teacup/merge_defaults.rb
teacup-0.3.3 lib/teacup/merge_defaults.rb
teacup-0.3.2 lib/teacup/merge_defaults.rb