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

.result
returns 0).

For example:

require 'erb'

ERB.new("<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result
ERB.new("<% 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
eout_var
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
binding
end
end

class Bar
def get_binding
binding
end
end

ERB.new("<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result(Foo.new.get_binding)
ERB.new("<% FOO = 'foo' %>\n<% BAR = 'bar' %>").result(Bar.new.get_binding)

Answer

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

Comments