Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterating properties #173

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Enhancements

- Added support for resolving superclass properties for not-NSObject subclasses
- You can now iterate objects and values of structs and tuples over their stored properties by their names and values

### Bug Fixes

Expand Down
10 changes: 5 additions & 5 deletions Sources/Context.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ public class Context {

public let environment: Environment

init(dictionary: [String: Any]? = nil, environment: Environment? = nil) {
init(dictionary: [String: Any?]? = nil, environment: Environment? = nil) {
if let dictionary = dictionary {
dictionaries = [dictionary]
} else {
Expand Down Expand Up @@ -37,7 +37,7 @@ public class Context {
}

/// Push a new level into the Context
fileprivate func push(_ dictionary: [String: Any]? = nil) {
fileprivate func push(_ dictionary: [String: Any?]? = nil) {
dictionaries.append(dictionary ?? [:])
}

Expand All @@ -47,14 +47,14 @@ public class Context {
}

/// 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, closure: (() throws -> Result)) rethrows -> Result {
public func push<Result>(dictionary: [String: Any?]? = nil, closure: (() throws -> Result)) rethrows -> Result {
push(dictionary)
defer { _ = pop() }
return try closure()
}

public func flatten() -> [String: Any] {
var accumulator: [String: Any] = [:]
public func flatten() -> [String: Any?] {
var accumulator: [String: Any?] = [:]

for dictionary in dictionaries {
for (key, value) in dictionary {
Expand Down
16 changes: 16 additions & 0 deletions Sources/ForTag.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,22 @@ class ForNode : NodeType {
values = Array(range)
} else if let range = resolved as? CountableRange<Int> {
values = Array(range)
} else if let resolved = resolved {
let mirror = Mirror(reflecting: resolved)
switch mirror.displayStyle {
case .struct?, .tuple?:
values = Array(mirror.children)
case .class?:
var children = Array(mirror.children)
var currentMirror: Mirror? = mirror
while let superclassMirror = currentMirror?.superclassMirror {
children.append(contentsOf: superclassMirror.children)
currentMirror = superclassMirror
}
values = Array(children)
default:
values = []
}
} else {
values = []
}
Expand Down
68 changes: 64 additions & 4 deletions Tests/StencilTests/ForNodeSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,22 +135,28 @@ func testForNode() {
let template = Template(templateString: templateString)
let result = try template.render(context)

let fixture = "one: I\ntwo: II\n\n"
try expect(result) == fixture
try expect(result.contains("one: I")).to.beTrue()
try expect(result.contains("two: II")).to.beTrue()
}

$0.it("renders supports iterating over dictionary") {
let nodes: [NodeType] = [VariableNode(variable: "key")]
let emptyNodes: [NodeType] = [TextNode(text: "empty")]
let node = ForNode(resolvable: Variable("dict"), loopVariables: ["key"], nodes: nodes, emptyNodes: emptyNodes, where: nil)
try expect(try node.render(context)) == "onetwo"

let result = try node.render(context)
try expect(result.contains("one")).to.beTrue()
try expect(result.contains("two")).to.beTrue()
}

$0.it("renders supports iterating over dictionary") {
let nodes: [NodeType] = [VariableNode(variable: "key"), VariableNode(variable: "value")]
let emptyNodes: [NodeType] = [TextNode(text: "empty")]
let node = ForNode(resolvable: Variable("dict"), loopVariables: ["key", "value"], nodes: nodes, emptyNodes: emptyNodes, where: nil)
try expect(try node.render(context)) == "oneItwoII"

let result = try node.render(context)
try expect(result.contains("oneI")).to.beTrue()
try expect(result.contains("twoII")).to.beTrue()
}

$0.it("handles invalid input") {
Expand All @@ -161,7 +167,61 @@ func testForNode() {
let error = TemplateSyntaxError("'for' statements should use the following 'for x in y where condition' `for i`.")
try expect(try parser.parse()).toThrow(error)
}

$0.it("iterates struct properties") {
struct MyStruct {
let string: String
let number: Int
}

let context = Context(dictionary: [
"struct": MyStruct(string: "abc", number: 123)
])

let nodes: [NodeType] = [VariableNode(variable: "property"), VariableNode(variable: "\":\""), VariableNode(variable: "value"),VariableNode(variable: "\";\"")]
let node = ForNode(resolvable: Variable("struct"), loopVariables: ["property", "value"], nodes: nodes, emptyNodes: [])
try expect(try node.render(context)) == "string:abc;number:123;"
}

$0.it("iterates tuple items") {
let context = Context(dictionary: [
"tuple": (one: 1, two: "dva"),
])

let nodes: [NodeType] = [VariableNode(variable: "label"), VariableNode(variable: "\":\""), VariableNode(variable: "value"),VariableNode(variable: "\";\"")]
let node = ForNode(resolvable: Variable("tuple"), loopVariables: ["label", "value"], nodes: nodes, emptyNodes: [])
try expect(try node.render(context)) == "one:1;two:dva;"
}

$0.it("iterates class properties") {
class MyClass {
var baseString: String
var baseInt: Int
init(_ string: String, _ int: Int) {
baseString = string
baseInt = int
}
}

class MySubclass: MyClass {
var childString: String
init(_ childString: String, _ string: String, _ int: Int) {
self.childString = childString
super.init(string, int)
}
}

let context = Context(dictionary: [
"class": MySubclass("child", "base", 1)
])

let nodes: [NodeType] = [VariableNode(variable: "label"), VariableNode(variable: "\":\""), VariableNode(variable: "value"),VariableNode(variable: "\";\"")]
let node = ForNode(resolvable: Variable("class"), loopVariables: ["label", "value"], nodes: nodes, emptyNodes: [])
try expect(try node.render(context)) == "childString:child;baseString:base;baseInt:1;"
}

}

}


Expand Down