summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBobby McDonald <bobbymcwho@gmail.com>2019-08-13 23:40:07 -0400
committerBobby McDonald <bobbymcwho@gmail.com>2019-08-14 12:31:10 -0400
commit157c3ecc6251e0033e71f97c874117976790db6d (patch)
tree2be90008aaf099e266119e76ce901426a0415e88
parent3e64a4f58d24b4741209b0678dbf62c00fe6cd03 (diff)
downloadhashie-157c3ecc6251e0033e71f97c874117976790db6d.tar.gz
Implement ruby 2.6 hash merging.
As of ruby 2.6, Hash#merge and Hash#merge! allow for multiple hashes to be passed to the method, and will merge each one in the order that they were passed.
-rw-r--r--lib/hashie/mash.rb35
-rw-r--r--spec/hashie/mash_spec.rb11
2 files changed, 41 insertions, 5 deletions
diff --git a/lib/hashie/mash.rb b/lib/hashie/mash.rb
index bac93a4..888b4f6 100644
--- a/lib/hashie/mash.rb
+++ b/lib/hashie/mash.rb
@@ -251,11 +251,39 @@ module Hashie
def deep_merge(other_hash, &blk)
dup.deep_update(other_hash, &blk)
end
- alias merge deep_merge
# Recursively merges this mash with the passed
# in hash, merging each hash in the hierarchy.
def deep_update(other_hash, &blk)
+ _deep_update(other_hash, &blk)
+ self
+ end
+
+ with_minimum_ruby('2.6.0') do
+ # Performs a deep_update on a duplicate of the
+ # current mash.
+ def deep_merge(*other_hashes, &blk)
+ dup.deep_update(*other_hashes, &blk)
+ end
+
+ # Recursively merges this mash with the passed
+ # in hash, merging each hash in the hierarchy.
+ def deep_update(*other_hashes, &blk)
+ other_hashes.each do |other_hash|
+ _deep_update(other_hash, &blk)
+ end
+ self
+ end
+ end
+
+ # Alias these lexically so they get the correctly defined
+ # #deep_merge and #deep_update based on ruby version.
+ alias merge deep_merge
+ alias deep_merge! deep_update
+ alias update deep_update
+ alias merge! update
+
+ def _deep_update(other_hash, &blk)
other_hash.each_pair do |k, v|
key = convert_key(k)
if v.is_a?(::Hash) && key?(key) && regular_reader(key).is_a?(Mash)
@@ -266,11 +294,8 @@ module Hashie
custom_writer(key, value, false)
end
end
- self
end
- alias deep_merge! deep_update
- alias update deep_update
- alias merge! update
+ private :_deep_update
# Assigns a value to a key
def assign_property(name, value)
diff --git a/spec/hashie/mash_spec.rb b/spec/hashie/mash_spec.rb
index 837a7f1..e2a178c 100644
--- a/spec/hashie/mash_spec.rb
+++ b/spec/hashie/mash_spec.rb
@@ -1046,4 +1046,15 @@ describe Hashie::Mash do
end
end
end
+
+ with_minimum_ruby('2.6.0') do
+ context 'ruby 2.6 merging' do
+ subject(:mash) { Hashie::Mash.new(model: 'Honda') }
+ it 'merges multiple hashes and mashes passeed to #merge' do
+ first_hash = { model: 'Ford' }
+ second_hash = { model: 'DeLorean' }
+ expect(mash.merge(first_hash, second_hash)).to eq('model' => 'DeLorean')
+ end
+ end
+ end
end