From 9b26b7d71a9ead3f6e3b8171a8af96db1b065be3 Mon Sep 17 00:00:00 2001 From: Kyle Fuller Date: Sat, 24 Oct 2015 17:27:02 -0700 Subject: [PATCH] [Context] Convenience push with block function --- Stencil/Context.swift | 8 ++++++++ StencilSpecs/ContextSpec.swift | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Stencil/Context.swift b/Stencil/Context.swift index 0f56cd72..02ee1e63 100644 --- a/Stencil/Context.swift +++ b/Stencil/Context.swift @@ -42,4 +42,12 @@ public class Context { public func pop() -> [String: Any]? { return dictionaries.popLast() } + + /// Push a new level onto the context for the duration of the execution of the given closure + public func push(dictionary: [String: Any]? = nil, @noescape closure: (() throws -> Result)) rethrows -> Result { + push(dictionary) + let result = try closure() + pop() + return result + } } diff --git a/StencilSpecs/ContextSpec.swift b/StencilSpecs/ContextSpec.swift index d16d01f5..20e81f78 100644 --- a/StencilSpecs/ContextSpec.swift +++ b/StencilSpecs/ContextSpec.swift @@ -50,4 +50,16 @@ describe("Context") { context.push(["name": "Katie"]) try expect(context["name"] as? String) == "Katie" } + + $0.it("allows you to push a dictionary and run a closure then restoring previous state") { + var didRun = false + + try context.push(["name": "Katie"]) { + didRun = true + try expect(context["name"] as? String) == "Katie" + } + + try expect(didRun).to.beTrue() + try expect(context["name"] as? String) == "Kyle" + } }