Ruby: How do I pass all parameters and blocks received by one method to another?
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.
Like this:
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 cal开发者_如何转开发l should make
# it all the way through to 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.
Is there a more 'Ruby-like' solution to this problem?
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
def method(...)
Starting from Ruby 2.7 it is possible to pass all the arguments of the current method to the other method using (...)
.
So, now,
def my_helper(*args, &block)
link_to(*args, &block)
# your code
end
can be rewritten as
def my_helper(...)
link_to(...)
# your code
end
Here is the link to the feature request.
精彩评论