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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement fetch_values for HashWithIndifferentAccess #28316

Merged
merged 1 commit into from Apr 10, 2017

Conversation

joshpencheon
Copy link
Contributor

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 HashWithIndifferentAccess, in line with the existing definitions of fetch and values_at.

Current behaviour, without patch:

hash = ActiveSupport::HashWithIndifferentAccess.new
hash[:a] = 'x'
hash[:b] = 'y'
hash.fetch_values('a', 'b') # => KeyError: key not found: "a"

New behaviour, with patch:

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"

Thanks, Josh

# hash.fetch_values('a', 'c') # => KeyError: key not found: "c"
def fetch_values(*indices, &block)
indices.collect { |key| fetch(key, &block) }
end
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's throw an if Hash.method_defined? :fetch_values onto the end here, so we don't get ahead of Hash.

(And a skip in the test to match)

`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`.
@joshpencheon
Copy link
Contributor Author

Thanks @matthewd, I hadn't considered that. I've made the changes you suggested; is there any formal way of documenting that these clauses can be removed once Ruby 2.3 is the minimum requirement?

I've rebased now development has moved to 5.2, and squashed my commits. Is there anything this PR needs?

@matthewd
Copy link
Member

Thanks!

is there any formal way of documenting that these clauses can be removed once Ruby 2.3 is the minimum requirement

Nope. I don't think we have enough of them to warrant a formal process... we'll just look for version-relevant conditionals (like method_defined? calls) when the time comes.

@matthewd matthewd merged commit 2144e70 into rails:master Apr 10, 2017
@sandstrom
Copy link
Contributor

I was just about to send a PR when I saw this! 😄 Great addition @joshpencheon!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants