Skip to content

Commit

Permalink
Fix deep_merge function, added custom implementation for pure Ruby
Browse files Browse the repository at this point in the history
  • Loading branch information
Skumring committed Nov 25, 2024
1 parent 8c5c0f3 commit 04f3dd5
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/valvat/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def dig(*keys)
end

def configure(options)
@data = @data.deep_merge(Utils.deep_symbolize_keys(options))
@data = Utils.deep_merge(@data, Utils.deep_symbolize_keys(options))
end

def initialize
Expand Down
5 changes: 5 additions & 0 deletions lib/valvat/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,10 @@ def self.deep_symbolize_keys(value)
val.is_a?(Hash) ? deep_symbolize_keys(val) : val
end
end

def self.deep_merge(original_hash, hash_to_merge)
merger = proc { |_key, v1, v2| v1.is_a?(Hash) && v2.is_a?(Hash) ? v1.merge(v2, &merger) : v2 }
original_hash.merge(hash_to_merge, &merger)
end
end
end
21 changes: 21 additions & 0 deletions spec/valvat/utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,25 @@
expect(described_class.deep_symbolize_keys({ 'a' => 1, :b => { 'c' => 3 } })).to eql({ a: 1, b: { c: 3 } })
end
end

describe '#deep_merge' do
let(:original_hash) { { a: 1, b: { c: 3 }, e: { w: 9 } } }
let(:hash_to_merge) { { b: { d: 4 }, e: { w: 10 }, y: 11 } }

it 'deep merge the nested hashes' do
expect(described_class.deep_merge(original_hash, hash_to_merge)).to eql(
{
a: 1,
b: {
c: 3,
d: 4
},
e: {
w: 10
},
y: 11
}
)
end
end
end

0 comments on commit 04f3dd5

Please sign in to comment.