From d4d74593fd18d3b99d7dc2473fe6c61e7d938c6d Mon Sep 17 00:00:00 2001 From: kenner kliemann Date: Wed, 30 Sep 2020 22:48:54 -0300 Subject: [PATCH] add hash slice using IndifferentAccess #529 --- CHANGELOG.md | 1 + lib/hashie/extensions/indifferent_access.rb | 5 +++++ spec/hashie/extensions/indifferent_access_spec.rb | 10 ++++++++++ 3 files changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2b77b79..15cedc72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ Any violations of this scheme are considered to be bugs. ### Fixed * [#516](https://github.com/hashie/hashie/issues/516): Fixed `NoMethodError` raised when including `Hashie::Extensions::Mash::SymbolizeKeys` and `Hashie::Extensions::SymbolizeKeys` in mashes/hashes with non string or symbol keys - [@carolineartz](https://github.com/carolineartz). +* [#](): Fixed [slice doesn't work using symbols](https://github.com/hashie/hashie/issues/529) using hash with `IndifferentAccess` extension - [@gnomex](https://github.com/gnomex) * Your contribution here. ### Security diff --git a/lib/hashie/extensions/indifferent_access.rb b/lib/hashie/extensions/indifferent_access.rb index f8176f5f..825609e7 100644 --- a/lib/hashie/extensions/indifferent_access.rb +++ b/lib/hashie/extensions/indifferent_access.rb @@ -141,6 +141,11 @@ def merge!(*) super.convert! end + def slice(*keys) + string_keys = keys.map { |key| convert_key(key) } + super(*string_keys) + end + protected def hash_lacking_indifference?(other) diff --git a/spec/hashie/extensions/indifferent_access_spec.rb b/spec/hashie/extensions/indifferent_access_spec.rb index 612f2760..f533785d 100644 --- a/spec/hashie/extensions/indifferent_access_spec.rb +++ b/spec/hashie/extensions/indifferent_access_spec.rb @@ -315,6 +315,16 @@ def indifferent_writer(key, value) end end end + + describe '#slice' do + let(:h) { subject.build(foo: 'bar', baz: 'qux') } + + it 'indifferently slices the hash' do + sliced_h = { 'foo' => 'bar' } + expect(h.slice('foo')).to eq sliced_h + expect(h.slice(:foo)).to eq sliced_h + end + end end describe 'with merge initializer' do