Permalink
Browse files

Add support for an optional block to Scope#evaluate.

  • Loading branch information...
1 parent 7f6c89e commit 01894929d4a52e27dae61a2e76030ce53c8755c2 @blambeau committed Jun 13, 2012
Showing with 18 additions and 4 deletions.
  1. +3 −0 CHANGELOG.md
  2. +10 −4 lib/wlang/scope.rb
  3. +5 −0 spec/unit/test_scope.rb
View
@@ -14,6 +14,9 @@
is the first argument of Dialect#render and Template#render. In Sinatra/Tilt situation,
this simply correspond to the `scope`, typically the Sinatra app.
+* Scope#evaluate now accepts an optional block for specifying a computed default value
+ instead of failing.
+
# 2.0.1 / 2012-06-12
* Fix support for 1.8.7 and jruby (undefined method `ord' for String)
View
@@ -43,10 +43,16 @@ def with(x)
yield(self.push(x))
end
- def evaluate(expr, *default)
- unfound = lambda{ default.empty? ? throw(:fail) : default.first }
- expr = expr.to_s.strip
- if expr.to_s.index('.').nil?
+ def evaluate(expr, *default, &bl)
+ expr = expr.to_s.strip
+ unfound = lambda do
+ if default.empty?
+ bl ? bl.call(expr) : throw(:fail)
+ else
+ default.first
+ end
+ end
+ if expr.index('.').nil?
fetch(expr.to_sym, &unfound)
else
keys = expr.split('.').map(&:to_sym)
@@ -55,6 +55,11 @@ module WLang
scope.evaluate(:nosuchone, 12).should eq(12)
end
+ it 'supports a default value through a block instead of fail' do
+ scope.evaluate(:nosuchone){ 12 }.should eq(12)
+ scope.evaluate(:nosuchone){ nil }.should be_nil
+ end
+
it 'supports nil as default value' do
scope.evaluate(:nosuchone, nil).should be_nil
end

0 comments on commit 0189492

Please sign in to comment.