I'm working on a bit of metaprogramming using send
methods quite a bit. I've been successful so far because the methods I'm send
ing to only take one argument.
我正在使用send方法进行一些元编程。到目前为止我已经成功了,因为我发送的方法只有一个参数。
Example:
client
is an API client
客户端是API客户端
@command
is a method on client
taken as an option to a CLI utility
@command是客户端上的一种方法,作为CLI实用程序的选项
@verb
is a method on command
taken as another option in the CLI
@verb是一种命令方法,作为CLI中的另一个选项
def command_keys
case @command
when "something"
self.command_options.slice(:some, :keys)
end
end
Then I call the API client like this:
然后我像这样调用API客户端:
client.send(@command).send(@verb, command_keys)
This works since the methods all take a Hash
as their argument. The problem I've run into is when I need to send more than 1 parameter in command_keys
. What I'm wondering is the best way to handle the command_keys
method returning more than 1 value. Example:
这是有效的,因为这些方法都以哈希为参数。我遇到的问题是当我需要在command_keys中发送多个参数时。我想知道的是处理command_keys方法返回多个值的最佳方法。例:
def command_keys
case @command
when "something"
return self.command_options[:some], self.command_options[:keys]
end
end
In this case, command_keys
returns an Array as expected, but when I try to pass that in the send(@verb, command_options)
call, it passes it as an Array (which is obviously expected). So, to make a long story short, is there some easy way to make this condition be handled easily?
在这种情况下,command_keys按预期返回一个数组,但是当我尝试在send(@verb,command_options)调用中传递它时,它将它作为一个数组传递(显然是期望的)。因此,总而言之,是否有一些简单的方法可以轻松处理这种情况?
I know send(@verb, argument1, argument2)
would get me the result I want, but I would like to be able to not have to give my script any more implementation logic than it needs, that is to say I would like it to remain as abstracted as possible.
我知道send(@verb,argument1,argument2)会得到我想要的结果,但是我希望能够不再给我的脚本提供比它需要的更多的实现逻辑,也就是说我想要它保持尽可能抽象。
1 个解决方案
#1
1
Use splat. You might have to rethink the code a bit, but something like:
使用splat。您可能需要重新考虑一下代码,但类似于:
client.send(@command).send(@verb, *all_the_args)
#1
1
Use splat. You might have to rethink the code a bit, but something like:
使用splat。您可能需要重新考虑一下代码,但类似于:
client.send(@command).send(@verb, *all_the_args)