Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how can I pass a parameter to the `capture` method?

In a Rails helper, you can capture the output of an ERB block using the capture method. However, what if the ERB block requires a parameter? How can I use capture in this case?

For a made-up example:

<% my_helper(:parameter, models) do |model| %>
  <%= model.eye_color %>
<% end %>

In the my_helper method, I want to surround the output of each iteration of the block with <span class='color'>...</span>.

I know I can capture the output of the ERB block and store it in a variable with html = capture(&block), but I don't know how to pass the necessary model parameter to that block!

like image 584
ClosureCowboy Avatar asked Aug 02 '11 05:08

ClosureCowboy


People also ask

Do arguments in Ruby get passed by reference or by value?

Pass-by-reference means that the arguments of a method are references to the variables that were passed into the method, and modifying the arguments modifies the original variables. If Ruby were pass-by-reference, changing the value of the argument (arg) would change the value of the variable val .

What is * args 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

Can you not pass them into the call to capture? The docs show that it splats arguments, so I would assume they get passed to the block. E.g:

html = capture(:foo, :bar, &block)
like image 166
coreyward Avatar answered Oct 10 '22 10:10

coreyward