From cfe3e6f3be197da14a1976fccb83cc1a33bb3add Mon Sep 17 00:00:00 2001 From: Brian Candler Date: Sat, 6 Jun 2009 16:04:22 +0100 Subject: [PATCH] Allow Hash with default value or default proc to be used --- lib/liquid/context.rb | 16 ++++++---------- test/variable_test.rb | 12 ++++++++++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/lib/liquid/context.rb b/lib/liquid/context.rb index 603cd55..0ba943b 100644 --- a/lib/liquid/context.rb +++ b/lib/liquid/context.rb @@ -159,16 +159,12 @@ module Liquid # fetches an object starting at the local scope and then moving up # the hierachy def find_variable(key) - @scopes.each do |scope| - if scope.has_key?(key) - variable = scope[key] - variable = scope[key] = variable.call(self) if variable.is_a?(Proc) - variable = variable.to_liquid - variable.context = self if variable.respond_to?(:context=) - return variable - end - end - nil + scope = @scopes[0..-2].find { |s| s.has_key?(key) } || @scopes.last + variable = scope[key] + variable = scope[key] = variable.call(self) if variable.is_a?(Proc) + variable = variable.to_liquid + variable.context = self if variable.respond_to?(:context=) + return variable end # resolves namespaced queries gracefully. diff --git a/test/variable_test.rb b/test/variable_test.rb index 20968ba..2ce846b 100644 --- a/test/variable_test.rb +++ b/test/variable_test.rb @@ -157,4 +157,16 @@ class VariableResolutionTest < Test::Unit::TestCase assert_equal 'bazbar', template.render end + def test_hash_with_default_proc + template = Template.parse(%|Hello {{ test }}|) + assigns = Hash.new { |h,k| raise "Unknown variable '#{k}'" } + assigns['test'] = 'Tobi' + assert_equal 'Hello Tobi', template.render!(assigns) + assigns.delete('test') + e = assert_raises(RuntimeError) { + template.render!(assigns) + } + assert_equal "Unknown variable 'test'", e.message + end + end \ No newline at end of file