diff --git a/lib/vagrant/util/template_renderer.rb b/lib/vagrant/util/template_renderer.rb index 463fce22c..7fc101fd6 100644 --- a/lib/vagrant/util/template_renderer.rb +++ b/lib/vagrant/util/template_renderer.rb @@ -35,13 +35,25 @@ module Vagrant # # @return [String] def render + # TODO: Seems like a pretty dirty way to do this. Perhaps refactor this + old_template = template result = nil File.open(full_template_path, 'r') do |f| - erb = ERB.new(f.read) - result = erb.result(binding) + self.template = f.read + result = render_string end result + ensure + self.template = old_template + end + + # Renders a template, handling the template as a string, but otherwise + # acting the same way as {#render}. + # + # @return [String] + def render_string + ERB.new(template).result(binding) end # Returns the full path to the template, taking into accoun the gem directory diff --git a/test/vagrant/util/template_renderer_test.rb b/test/vagrant/util/template_renderer_test.rb index 963e33a02..2820ee512 100644 --- a/test/vagrant/util/template_renderer_test.rb +++ b/test/vagrant/util/template_renderer_test.rb @@ -24,9 +24,6 @@ class TemplateRendererUtilTest < Test::Unit::TestCase @file = mock("file") @file.stubs(:read).returns(@contents) File.stubs(:open).yields(@file) - - @erb = mock("erb") - @erb.stubs(:result) end should "open the template file for reading" do @@ -34,15 +31,13 @@ class TemplateRendererUtilTest < Test::Unit::TestCase @r.render end - should "create an ERB object with the file contents" do - ERB.expects(:new).with(@file.read).returns(@erb) - @r.render - end + should "set the template to the file contents, render, then set it back" do + result = "bar" - should "render the ERB file and return the results" do - result = mock("result") - ERB.expects(:new).returns(@erb) - @erb.expects(:result).with(anything).once.returns(result) + template_seq = sequence("template_seq") + @r.expects(:template=).with(@file.read).in_sequence(template_seq) + @r.expects(:render_string).returns(result).in_sequence(template_seq) + @r.expects(:template=).with(@template).in_sequence(template_seq) assert_equal result, @r.render end @@ -55,6 +50,21 @@ class TemplateRendererUtilTest < Test::Unit::TestCase end end + context "rendering as string" do + setup do + @result = "foo" + @erb = mock("erb") + @erb.stubs(:result).returns(@result) + + @r = Vagrant::Util::TemplateRenderer.new("foo") + end + + should "simply render the template as a string" do + ERB.expects(:new).with(@r.template).returns(@erb) + assert_equal @result, @r.render_string + end + end + context "the full template path" do setup do @template = "foo"