Using (: send) in Ruby with keyword arguments?

I have a private method that I'm trying to use #send in Ruby to do some testing. The method is complex, and I do not want it to be open outside the class, so I want to test this method, but I also do not need to specify it as a public method. It has keyword arguments. How can I use send to invoke a method, but also pass keyword arguments / named parameters to it? Is there any way?

The method is as follows:

def some_method(keyword_arg1:, keyword_arg2:, keyword_arg3: nil)

+5
source share
1 answer

Depends on how the args keywords are defined.

If they are defined for any reason, pass them inline:

 SomeClass.send(:some_method, {keyword_arg1: 'foo', keyword_arg2: 'bar'}) 

If they are defined in the hash, you can unpack it:

 hash = {keyword_arg1: 'baz', keyword_arg2: 'bing'} SomeClass.send(:some_method, **hash) 
+11
source

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


All Articles