Skip to content

Commit

Permalink
[Context] Convenience push with block function
Browse files Browse the repository at this point in the history
  • Loading branch information
kylef committed Oct 26, 2015
1 parent 19366ec commit 9b26b7d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Stencil/Context.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result>(dictionary: [String: Any]? = nil, @noescape closure: (() throws -> Result)) rethrows -> Result {
push(dictionary)
let result = try closure()
pop()
return result
}
}
12 changes: 12 additions & 0 deletions StencilSpecs/ContextSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}

0 comments on commit 9b26b7d

Please sign in to comment.