Skip to content

Commit

Permalink
Merge pull request #525 from yogeshjain999/indifferent-convert-change
Browse files Browse the repository at this point in the history
Small amendments for Hash#merge with IndifferentAccess
  • Loading branch information
dblock committed Jun 10, 2020
2 parents 694f2e7 + b206fb8 commit c95b261
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 }.freeze

# 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 c95b261

Please sign in to comment.