1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Implement fetch_values for HashWithIndifferentAccess (#28316)

`fetch_values` was added to Hash in Ruby 2.3.0:
  https://bugs.ruby-lang.org/issues/10017

This patch adds an implemention for instances of HWAI, in line
with the existing definitions of `fetch` and `values_at`.
This commit is contained in:
Josh Pencheon 2017-04-10 01:50:13 +01:00 committed by Matthew Draper
parent 24ac36be71
commit 2144e70a86
3 changed files with 31 additions and 0 deletions

View file

@ -1 +1,7 @@
* Add `fetch_values` for `HashWithIndifferentAccess`
The method was originally added to `Hash` in Ruby 2.3.0.
*Josh Pencheon*
Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activesupport/CHANGELOG.md) for previous changes.

View file

@ -195,6 +195,19 @@ module ActiveSupport
indices.collect { |key| self[convert_key(key)] }
end
# Returns an array of the values at the specified indices, but also
# raises an exception when one of the keys can't be found.
#
# hash = ActiveSupport::HashWithIndifferentAccess.new
# hash[:a] = 'x'
# hash[:b] = 'y'
# hash.fetch_values('a', 'b') # => ["x", "y"]
# hash.fetch_values('a', 'c') { |key| 'z' } # => ["x", "z"]
# hash.fetch_values('a', 'c') # => KeyError: key not found: "c"
def fetch_values(*indices, &block)
indices.collect { |key| fetch(key, &block) }
end if Hash.method_defined?(:fetch_values)
# Returns a shallow copy of the hash.
#
# hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } })

View file

@ -166,6 +166,18 @@ class HashWithIndifferentAccessTest < ActiveSupport::TestCase
assert_equal [1, 2], @mixed.values_at(:a, :b)
end
def test_indifferent_fetch_values
skip unless Hash.method_defined?(:fetch_values)
@mixed = @mixed.with_indifferent_access
assert_equal [1, 2], @mixed.fetch_values("a", "b")
assert_equal [1, 2], @mixed.fetch_values(:a, :b)
assert_equal [1, 2], @mixed.fetch_values(:a, "b")
assert_equal [1, "c"], @mixed.fetch_values(:a, :c) { |key| key }
assert_raise(KeyError) { @mixed.fetch_values(:a, :c) }
end
def test_indifferent_reading
hash = HashWithIndifferentAccess.new
hash["a"] = 1