Skip to content

Commit

Permalink
new template rendering option: :scope - eval in a scope other than self
Browse files Browse the repository at this point in the history
Signed-off-by: Konstantin Haase <konstantin.mailinglists@googlemail.com>
  • Loading branch information
Paul Walker authored and rkh committed Feb 19, 2011
1 parent 9db223e commit 8c00771
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/sinatra/base.rb
Expand Up @@ -483,17 +483,18 @@ def render(engine, data, options={}, locals={}, &block)
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

Expand Down
17 changes: 17 additions & 0 deletions test/templates_test.rb
Expand Up @@ -229,6 +229,23 @@ def with_default_layout
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.
Expand Down

0 comments on commit 8c00771

Please sign in to comment.