From dc6e32a5cea29e9055463f6eff84f2b829a19c1c Mon Sep 17 00:00:00 2001 From: Chris Schneider Date: Tue, 27 May 2008 20:09:45 -0600 Subject: [PATCH] Add :locals option for erb. General approach and some of the code was borrowed from rails (compilable.rb) --- lib/sinatra.rb | 14 ++++++++++++-- test/erb_test.rb | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index fb0af36d..439a8f43 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -576,9 +576,19 @@ module Sinatra private def render_erb(content, options = {}) - ::ERB.new(content).result(binding) + locals_opt = options.delete(:locals) || {} + + locals_code = "" + locals_hash = {} + locals_opt.each do |key, value| + locals_code << "#{key} = locals_hash[:#{key}]\n" + locals_hash[:"#{key}"] = value + end + + body = ::ERB.new(content).src + eval("#{locals_code}#{body}", binding) end - + end module Haml diff --git a/test/erb_test.rb b/test/erb_test.rb index 81e79eba..36c1e239 100644 --- a/test/erb_test.rb +++ b/test/erb_test.rb @@ -23,6 +23,26 @@ context "Erb" do body.should == '2' end + + specify "should take an options hash with :locals set with a string" do + get '/locals' do + erb '<%= foo %>', :locals => {:foo => "Bar"} + end + + get_it '/locals' + should.be.ok + body.should == 'Bar' + end + + specify "should take an options hash with :locals set with a complex object" do + get '/locals-complex' do + erb '<%= foo[0] %>', :locals => {:foo => ["foo", "bar", "baz"]} + end + + get_it '/locals-complex' + should.be.ok + body.should == 'foo' + end end context "with layouts" do