ERB provides an easy to use but powerful templating system for Ruby. Using ERB, Ruby code can be added to any plain text document for the purposes of generating document information details and/or flow control.

The following code substitutes variables into a template string with erb. It uses Kernel#binding method to get the current context.

require 'erb'

name = 'Akshay'
age = 30

erb = ERB.new 'My name is <%= name %> and I am <%= age %> years old'
puts erb.result(binding)

# Output:
#
# "My name is Akshay and I am 30 years old"

Note the <%= title %> statement. Within an erb template, Ruby code can be included using both <% %> and <%= %> tags.

The <% %> tags are used to execute Ruby code that does not return anything, such as conditions, loops, or blocks, and the <%= %> tags are used when you want to output the result.

What's going on in the above example?

  1. After requiring the ERB gem and creating a few variables, we create an instance of the ERB class with a template string.

  2. We create a Binding object by calling the Kernel#binding method. Again, think of the binding object as a wrapper that includes the current programming environment with variables like name and age, methods, and even the self object.

  3. The result method on the erb object uses this binding object and the variables defined in that binding to replace the slots in the template string, generating the final string printed above.

I hope that you now have a good understanding of the concept of binding. The basic idea behind binding is to store the current context in an object for later use. To tie it back to our web application, we'll use binding of a controller action method to access the instance variables in the view.

However, the concept of binding also extends to the instance variables of a class. That means if you get the binding in the scope of an instance of a class, it contains the instance variables which you can use in an ERB template. The following example will make it clear.

require 'erb'

class Person
  def initialize
    @name = 'Akshay'
    @age = 30
  end

  def get_binding
    binding
  end
end

ak = Person.new

erb = ERB.new 'My name is <%= @name %> and I am <%= @age %> years old'
puts erb.result(ak.get_binding)

# Output
# ======
# My name is Akshay and I am 30 years old

In the above code, the Person#get_binding method returns the binding of an instance of the Person class. When we call ak.get_binding, it returns the binding of the instance ak and contains the instance variables @name and @age, which ERB uses to fill the string template.

Now that you understand how a template can access the instance variables of a class, let's go back to the original problem: accessing controller instance variables in the view template. We'll implement it in three simple steps.