Ruby:如何将一种方法接收到的所有参数和块传递给另一种方法? [英] Ruby: How do I pass all parameters and blocks received by one method to another?

查看:33
本文介绍了Ruby:如何将一种方法接收到的所有参数和块传递给另一种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个帮助程序,它将 HTML 属性添加到 rails 中的 link_to 标记.所以,我的想法是我的辅助方法应该接受传递给它的任何参数或块,使用这些相同的参数调用 link_to,将它的属性添加到返回的内容中,并将结果返回给调用者.

I am writing a helper that adds an HTML attribute to a link_to tag in rails. So, my thinking is that my helper method should accept any parameters or blocks passed to it, call link_to with those same parameters, add it's attribute to what is returned, and return the result to the caller.

像这样:

def link_to(*args, &block)
  ... rails code in link_to ...
end

def myhelper(*args, &block) # Notice that at this point, 'args' has already
  link_to()                 # become an array of arguments and 'block' has
  ... my code ...           # already been turned into a Proc.
end

myhelper() # Any arguments or blocks I pass with this call should make
           # it all the way through to link_to.

因此,如您所见,似乎没有办法(不涉及大量代码和条件分支)将 myhelper 收到的内容传递给 link_to,而不会将所有参数恢复为之前的样子他们采用了我的方法.

So, as you can see, there seems to be no way (that doesn't involve lots of code and conditional branching) to pass what myhelper has received to link_to without turning all of the parameters back into what they looked like before they got to my method.

对于这个问题,是否有更类似 Ruby"的解决方案?

Is there a more 'Ruby-like' solution to this problem?

推荐答案

您可以在方法调用中使用 *& 将数组转回参数列表和procs 回到块中.所以你可以这样做:

You can use * and & in method calls to turn arrays back into lists of arguments and procs back into blocks. So you can just do this:

def myhelper(*args, &block)
  link_to(*args, &block)
  # your code
end

这篇关于Ruby:如何将一种方法接收到的所有参数和块传递给另一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆