Skip to content

Commit

Permalink
fix(variable): Prevent crash on unknown index in array
Browse files Browse the repository at this point in the history
  • Loading branch information
kylef committed Oct 13, 2016
1 parent 72f3cb5 commit 1e3afc0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
# Stencil Changelog

## Master

### Bug Fixes

- Variables (`{{ variable.5 }}`) that reference an array index at an unknown
index will now resolve to `nil` instead of causing a crash.
[#72](https://github.com/kylef/Stencil/issues/72)


## 0.6.0

### Enhancements
Expand Down
6 changes: 5 additions & 1 deletion Sources/Variable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ public struct Variable : Equatable, Resolvable {
current = dictionary[bit]
} else if let array = current as? [Any] {
if let index = Int(bit) {
current = array[index]
if index >= 0 && index < array.count {
current = array[index]
} else {
current = nil
}
} else if bit == "first" {
current = array.first
} else if bit == "last" {
Expand Down
14 changes: 14 additions & 0 deletions Tests/StencilTests/VariableSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ func testVariable() {
let variable = Variable("contacts.0")
let result = try variable.resolve(context) as? String
try expect(result) == "Katie"

let variable1 = Variable("contacts.1")
let result1 = try variable1.resolve(context) as? String
try expect(result1) == "Carlton"
}

$0.it("can resolve an item from an array via unknown index") {
let variable = Variable("contacts.5")
let result = try variable.resolve(context) as? String
try expect(result).to.beNil()

let variable1 = Variable("contacts.-5")
let result1 = try variable1.resolve(context) as? String
try expect(result1).to.beNil()
}

$0.it("can resolve the first item from an array") {
Expand Down

0 comments on commit 1e3afc0

Please sign in to comment.