Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 352
marcusM Avatar asked Jan 13 '11 18:01

marcusM


People also ask

How do you pass block to method in Ruby?

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.

How are the arguments in Ruby passed?

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.

What does * args mean in Ruby?

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).


1 Answers

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 
like image 181
sepp2k Avatar answered Sep 17 '22 10:09

sepp2k