我正在编写一个帮助程序,将 HTML 属性添加到 Rails 中的 link_to 标记中。因此,我的想法是,我的辅助方法应该接受传递给它的任何参数或块,使用这些相同的参数调用 link_to,将其属性添加到返回的内容中,并将结果返回给调用者。
像这样:
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,而不将所有参数恢复为它们之前的样子我的方法。
对于这个问题,是否有更“类似 Ruby”的解决方案?
您可以使用*
and &
在方法调用中将数组转回参数列表,将过程转回块。所以你可以这样做:
def myhelper(*args, &block)
link_to(*args, &block)
# your code
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)