Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small amendments for Hash#merge with IndifferentAccess #525

Merged
merged 1 commit into from Jun 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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