Permalink
Browse files

Raise error on locals with non-variable key

Rather than swallowing invalid locals, notify the user something is wrong.
Among other things this will allow the user to more easily identify errors in
their template.
  • Loading branch information...
1 parent 3b6b9e2 commit d4c67207dbc02aced72b13ddd1b1f0e8b08b2526 Simon Chiang committed Nov 29, 2012
Showing with 11 additions and 5 deletions.
  1. +7 −1 lib/tilt/template.rb
  2. +4 −4 test/tilt_template_test.rb
View
8 lib/tilt/template.rb
@@ -186,7 +186,13 @@ def precompiled_template(locals)
# source line offset, so adding code to the preamble does not effect line
# reporting in Kernel::caller and backtraces.
def precompiled_preamble(locals)
- locals.map { |k,v| k.to_s =~ /\A[a-z]\w*\z/ ? "#{k} = locals[#{k.inspect}]" : nil }.join("\n")
+ locals.map do |k,v|
+ if k.to_s =~ /\A[a-z]\w*\z/
+ "#{k} = locals[#{k.inspect}]"
+ else
+ raise "invalid locals key: #{k.inspect} (keys must be variable names)"
+ end
+ end.join("\n")
end
# Generates postamble code for the precompiled template source. The
View
8 test/tilt_template_test.rb
@@ -134,10 +134,10 @@ def precompiled_template(locals)
assert inst.prepared?
end
- test "template_source with locals of invalid variable names" do
- inst = SourceGeneratingMockTemplate.new { |t| '1 + 2 = #{Math::PI.to_i}' }
- assert_equal "1 + 2 = 3", inst.render(Object.new, 'Math::PI' => '42')
- assert inst.prepared?
+ test "template_source with locals having non-variable keys raises error" do
+ inst = SourceGeneratingMockTemplate.new { |t| '1 + 2 = #{ANSWER}' }
+ err = assert_raise(RuntimeError) { inst.render(Object.new, 'ANSWER' => '3') }
+ assert_equal "invalid locals key: \"ANSWER\" (keys must be variable names)", err.message
end
class Person

0 comments on commit d4c6720

Please sign in to comment.