Matt S. Matt S. - 6 months ago 20
Ruby Question

Creating separate templates with ERB

I need to be able to create distinct templates using ERB instead of having them all appended sequentially (assuming

returns 0).

For example:

require 'erb'"<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result"<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result

Returns the following warnings:

(erb):1: warning: already initialized constant FOO
(erb):1: warning: previous definition of FOO was here
(erb):2: warning: already initialized constant BAR
(erb):2: warning: previous definition of BAR was here

proving that the second ERB is appending onto the first, or that some other shenanigans are occurring here. I have tried various routes with the bindings and
to of no avail.

How do I get ruby to understand these are two distinct templates and not two parts of a whole?

Given the accepted answer, this would be the solution for my contrived example of the problem:

require 'erb'

class Foo
def get_binding

class Bar
def get_binding
end"<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result("<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result(


FOO/BAR constants live in ruby itself, not in templates, thus redefinition warning.

If you need different values for a constant then it's obviously not a constant. If values are the same - then there's no point in multiple definitions

Also look into passing a binding to result, by default it's a top level scope, but can be changed