9

Suppose I have a Ruby ERB template named my_template.html.erb, and it contains the following:

<div><%= @div_1 %></div>
<div><%= @div_2 %></div>
<div><%= @div_3 %></div>

Is there a way I can programatically list out all the available variables in the template?

For example, the following method:

def list_out_variables
  template = File.open("path_to/my_template.html.erb", "rb").read
  erb = ERB.new( template )
  erb.this_method_would_list_out_variables  
end

would return something like:

['div1','div2','div3']

Any help would be greatly appreciated.

Thanks, Mike

1
  • 1
    Don't know if it's actually possible, but it seems like a bad idea to me. Normally, view depends on controller, not other way around. Sep 27, 2010 at 1:08

1 Answer 1

27

To get a list of variables available to your .erb file (from the controller):

Add a breakpoint in the erb:

<% debugger %>

Then type instance_variables in the debugger to see all of the available instance variables.

Added: Note that instance_variables is a method available from the Ruby class Object and all of its subclasses. (As noted by @mikezter.) So you could call the method programmatically from within your sw rather than using the debugger if you really wanted to.

You'll get back a list of instance variables for the current object.

Added: To get a list of the variables used by an .erb file:

# <template> is loaded with the entire contents of the .erb file as
# one long string
var_array = template.scan(/(\@[a-z]+[0-9a-z]*)/i).uniq
3
  • 4
    @mikezter: -1? Seems a bit harsh. The debugger docs (see link in answer) aren't so clear. I would have upvoted your comment if you'd simply pointed out that typing instance_variables in the debugger is really sending that method name to the current object.
    – Larry K
    Sep 27, 2010 at 21:45
  • Thanks for the help! For anyone else: the capture group within the regex (the parenthesis) is unnecessary, and causes a nested array instead of just an array of the variable names. Aug 11, 2016 at 21:50
  • I just add <%= instance_variables %> to the .erb file to check them.
    – PhilCowan
    Nov 14, 2022 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.