Created
June 13, 2010 04:13
-
-
Save DohMoose/436339 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def test_deep_merge | |
@ordered_hash['deep'] = ActiveSupport::OrderedHash.new | |
@ordered_hash['deep']['number'] = 1 | |
@ordered_hash['deep']['place'] = 'here' | |
other_hash = ActiveSupport::OrderedHash.new | |
other_hash['deep'] = ActiveSupport::OrderedHash.new | |
other_hash['deep']['number'] = 5 | |
merged = @ordered_hash.deep_merge(other_hash) | |
#should merge the nested hash | |
assert_equal 5, merged['deep']['number'] | |
assert_equal 'here', merged['deep']['place'] | |
end | |
def test_deep_block_merge | |
@ordered_hash['deep'] = ActiveSupport::OrderedHash.new | |
@ordered_hash['deep']['number'] = 1 | |
other_hash = ActiveSupport::OrderedHash.new | |
other_hash['deep'] = ActiveSupport::OrderedHash.new | |
other_hash['deep']['number'] = 5 | |
other_hash['deep']['place'] = 'here' | |
merged = @ordered_hash.deep_merge(other_hash){|key, old_value, new_value| old_value + new_value} | |
#should merge the nested hash | |
assert_equal 6, merged['deep']['number'] | |
assert_equal 'here', merged['deep']['place'] | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hash | |
# Returns a new hash with +self+ and +other_hash+ merged recursively. | |
def deep_merge(other_hash, &block) | |
dup.deep_merge!(other_hash, &block) | |
end | |
# Returns a new hash with +self+ and +other_hash+ merged recursively. | |
# Modifies the receiver in place. | |
def deep_merge!(other_hash, &block) | |
other_hash.each_pair do |k,v| | |
tv = self[k] | |
if tv.is_a?(Hash) && v.is_a?(Hash) | |
self[k] = tv.deep_merge(v, &block) | |
else | |
if block_given? and (!tv.nil? and !v.nil?) | |
self[k] = yield(k, tv, v) | |
else | |
self[k] = v | |
end | |
end | |
end | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment