Is there a way to list the available variables in a Ruby ERB template?

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 that I can programmatically display all available variables in a 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 

will return something like:

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

Any help would be greatly appreciated.

Thanks Mike

+6
ruby ruby-on-rails erb
source share
1 answer

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

Add a breakpoint to erb:

 <% debugger %> 

Then enter instance_variables in the debugger to view all available instance variables.

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

You will get a list of instance variables for the current object.

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

 # <template> is loaded with the entire contents of the .erb file as # one long string var_array = template.scan(/(\@[az]+[0-9a-z]*)/i).uniq 
+22
source share

All Articles