Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to list the available variables in an 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 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

like image 286
Mike G Avatar asked Sep 27 '10 01:09

Mike G


People also ask

What does ERB do in Ruby?

ERB (or Ruby code generated by ERB) returns a string in the same character encoding as the input string. When the input string has a magic comment, however, it returns a string in the encoding specified by the magic comment.

What is an ERB template?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.

What is ERB in Ruby on Rails?

ERB is a templating engine. A templating engine allows you to mix HTML & Ruby so you can generate web pages using data from your database. ERB is Rails default engine for rendering views. Note: Rails uses an implementation called erubi instead of the ERB class from the Ruby standard library.


1 Answers

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
like image 146
Larry K Avatar answered Jan 25 '23 23:01

Larry K