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 call 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?
In Ruby, methods can take blocks implicitly and explicitly. Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don't have to add the block to the list of arguments the method accepts.
In ruby, arguments inside a method are passed by reference In ruby, we have a different situation, the variable that we have inside the method stores a reference to an object. Thus, if we will change an object inside the method, then it will be changed also outside the method.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With