Skip to content

Commit

Permalink
Small amendments for Hash#merge with IndifferentAccess
Browse files Browse the repository at this point in the history
1. Use `indifferent_writer` in `convert!` so that when
`indifferent_writer`, `convert_key` or `indifferent_value` is
overridden in included class, `merge` can use those.

2. `convert!` was calling twice if `other` hash was lacking
indifference. `IndifferentAccess.inject!` already does conversion.
  • Loading branch information
yogeshjain999 committed Jun 10, 2020
1 parent c066135 commit 747c9cb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/hashie/extensions/indifferent_access.rb
Expand Up @@ -74,7 +74,7 @@ def convert_key(key)
# is injecting itself into member hashes.
def convert!
keys.each do |k| # rubocop:disable Performance/HashEachMethods
regular_writer convert_key(k), indifferent_value(regular_delete(k))
indifferent_writer k, regular_delete(k)
end
self
end
Expand Down Expand Up @@ -133,7 +133,7 @@ def indifferent_replace(other_hash)

def merge(*args)
result = super
IndifferentAccess.inject!(result) if hash_lacking_indifference?(result)
return IndifferentAccess.inject!(result) if hash_lacking_indifference?(result)
result.convert!
end

Expand Down
39 changes: 39 additions & 0 deletions spec/hashie/extensions/indifferent_access_spec.rb
Expand Up @@ -86,6 +86,45 @@ class IndifferentHashWithIgnoreUndeclaredAndPropertyTranslation < Hashie::Dash
end
end

describe 'when overriding indifferent methods' do
let(:indifferent_hash) do
Class.new(::Hash) do
include Hashie::Extensions::IndifferentAccess

ALIASES = { cat: :grumpy }

# Override writer to maintain alias of the given key
def indifferent_writer(key, value)
indifferent_value = indifferent_value(value)

regular_writer convert_key(key), indifferent_value
regular_writer convert_key(ALIASES[key]), indifferent_value
end
alias_method :[]=, :indifferent_writer
end.new
end

it '#indifferent_writer' do
indifferent_hash[:cat] = 'meow'

expect(indifferent_hash[:cat]).to eq('meow')
expect(indifferent_hash['cat']).to eq('meow')

expect(indifferent_hash[:grumpy]).to eq('meow')
expect(indifferent_hash['grumpy']).to eq('meow')
end

it '#merge' do
merged_hash = indifferent_hash.merge(cat: 'meow')

expect(merged_hash[:cat]).to eq('meow')
expect(merged_hash['cat']).to eq('meow')

expect(merged_hash[:grumpy]).to eq('meow')
expect(merged_hash['grumpy']).to eq('meow')
end
end

describe 'when translating properties and ignoring undeclared' do
let(:value) { 'baz' }

Expand Down

0 comments on commit 747c9cb

Please sign in to comment.