Jano Svitok
12/8/2006 2:08:00 PM
On 12/8/06, Jeremy Wells <jwells@servalsystems.co.uk> wrote:
> surely this won't work as the binding in my case is coming from an
> external source, so the ruby in the eval won't have access to the
> variable in the render method?
So once more: The trick is to use eval with binding as an additional argument.
That means when eval gets a binding as the second argument, it will operate
in that context. In this case, if you eval("@var = 123",
some_binding), the variable @var will be set in that binding.
Beware that you are modifying the original binding, so you might
corrupt the original caller.
Maybe @binding = apply_binding.dup will be neccessary.
(I added @ in the template - it was missing)
require 'erb'
# TEMPLATE = "<xml><%=@variable1%> <%=variable2%></xml>"
TEMPLATE = "<xml><%=@variable1%> <%=@variable2%></xml>"
class Renderer
def initialize(template_file, apply_binding)
@file = template_file
@binding = apply_binding
end
def render
# @variable2 = "There"
eval("@variable2 = \"There\"", @binding)
# template = ERB.new(File.read(@file))
template = ERB.new(TEMPLATE)
template_results = template.result(@binding)
# Perform on template results
template_results
end
end
require 'test/unit'
class TestERB < Test::Unit::TestCase
def test_variable
@variable1 = "Hello"
renderer = Renderer.new('template.xml', binding)
assert_equal "<xml>Hello There</xml>", renderer.render
end
end