Ruby Hash.merge with specified keys

I'm sure I saw something like this on a Rails-related site:

def my_function(*opts) opts.require_keys(:first, :second, :third) end 

And if one of the keys in require_keys not specified or keys were specified that were not specified, an exception was thrown. I was browsing ActiveSupport, and I think I could look for something like the reverse of except .

I like to try to use as much of the structure as possible compared to writing my own code, so I ask the question when I know how to make the same functionality on my own. :)

At the moment, I am doing this through the usual merge procedure and make sure that I have what I need with some IFs.

+4
source share
2 answers

You can do it yourself relatively easily. As mentioned in an earlier answer, half of your work is done for you in assert_valid_keys . You can flip your own method to do the rest.

 def my_function( *opts ) opts.require_and_assert_keys( :first, :second, :third ) end 

create lib/hash_extensions.rb with the following:

 class Hash def require_and_assert_keys( *required_keys ) assert_valid_keys( keys ) missing_keys = required_keys.inject(missing=[]) do |missing, key| has_key?( key ) ? missing : missing.push( key ) end raise( ArgumentError, "Missing key(s): #{missing_keys.join( ", ")}" ) unless missing_keys.empty? end end 

Finally, in config/environment.rb add this to make it work:

 require 'hash_extensions' 
+1
source

Source: https://habr.com/ru/post/1310943/


All Articles