From 8c00771486b902ec0ed6fbb8632288d04019b095 Mon Sep 17 00:00:00 2001 From: Paul Walker Date: Sat, 19 Feb 2011 14:10:18 +0100 Subject: [PATCH] new template rendering option: :scope - eval in a scope other than self Signed-off-by: Konstantin Haase --- lib/sinatra/base.rb | 5 +++-- test/templates_test.rb | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 89dd8fcf..b7d33228 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -483,17 +483,18 @@ module Sinatra layout = @default_layout if layout.nil? or layout == true content_type = options.delete(:content_type) || options.delete(:default_content_type) layout_engine = options.delete(:layout_engine) || engine + scope = options.delete(:scope) || self # compile and render template layout_was = @default_layout @default_layout = false template = compile_template(engine, data, options, views) - output = template.render(self, locals, &block) + output = template.render(scope, locals, &block) @default_layout = layout_was # render layout if layout - options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors) + options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors, :scope => scope) catch(:layout_missing) { output = render(layout_engine, layout, options, locals) { output }} end diff --git a/test/templates_test.rb b/test/templates_test.rb index 43f4aa1a..0cef50b9 100644 --- a/test/templates_test.rb +++ b/test/templates_test.rb @@ -229,6 +229,23 @@ class TemplatesTest < Test::Unit::TestCase render_app { render :erb, :calc } assert_equal '2', body end + + it "passes scope to the template" do + mock_app { + template :scoped do + 'Hello <%= foo %>' + end + + get '/' do + some_scope = Class.new; def foo; 'World!'; end; + erb :scoped, :scope => some_scope + end + } + + get '/' + assert ok? + assert_equal 'Hello World!', body + end end # __END__ : this is not the real end of the script.