Skip to content

Instantly share code, notes, and snippets.

@stephancom
Created March 24, 2017 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephancom/6f0ac16184279c45be0f86c8886d038f to your computer and use it in GitHub Desktop.
Save stephancom/6f0ac16184279c45be0f86c8886d038f to your computer and use it in GitHub Desktop.
recursive hash keys
# Returns keys from a hash recursively when that hash can contain hashes
# Handy for use with StrongParameters
recurse_keys = lambda do |h| h.inject([]) { |a, (k, v)| a << (v.is_a?(Hash) ? { k => recurse_keys.call(v) } : k) } rescue [] end
# Example
parms = {:foo=>:bar, :baz=>{:a=>:b, :c=>:d, :e=>:f}}
recurse_keys.call(parms)
# returns [:foo, {baz: [:a, :b, :c]}]
@stephancom
Copy link
Author

This would be handy for implementing strong_parameters permit! on certain keys as discussed here:

rails/rails#9454

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