Skip to content

Commit

Permalink
Enable nested context to be injected when unboxing a nested Unboxable
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnSundell committed Jul 25, 2016
1 parent ca8ae1d commit f8568ce
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
8 changes: 4 additions & 4 deletions Sources/Unbox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -619,16 +619,16 @@ public class Unboxer {
}

/// Unbox a required nested Unboxable, by unboxing a Dictionary and then using a transform
public func unbox<T: Unboxable>(key: String, isKeyPath: Bool = true) -> T {
public func unbox<T: Unboxable>(key: String, isKeyPath: Bool = true, context: Any? = nil) -> T {
return UnboxValueResolver<UnboxableDictionary>(self).resolveRequiredValueForKey(key, isKeyPath: isKeyPath, fallbackValue: T.unboxFallbackValue(), transform: {
return try? Unbox($0, context: self.context)
return try? Unbox($0, context: context ?? self.context)
})
}

/// Unbox an optional nested Unboxable, by unboxing a Dictionary and then using a transform
public func unbox<T: Unboxable>(key: String, isKeyPath: Bool = true) -> T? {
public func unbox<T: Unboxable>(key: String, isKeyPath: Bool = true, context: Any? = nil) -> T? {
return UnboxValueResolver<UnboxableDictionary>(self).resolveOptionalValueForKey(key, isKeyPath: isKeyPath, transform: {
return try? Unbox($0, context: self.context)
return try? Unbox($0, context: context ?? self.context)
})
}

Expand Down
34 changes: 34 additions & 0 deletions Tests/UnboxTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,40 @@ class UnboxTests: XCTestCase {
XCTFail("Failed to unbox")
}
}

func testNestedUnboxableContext() {
struct Model: Unboxable {
let nested: NestedModel

init(unboxer: Unboxer) {
self.nested = unboxer.unbox("nested", context: "Context")
}
}

struct NestedModel: Unboxable {
let context: Any?

init(unboxer: Unboxer) {
self.context = unboxer.context
}
}

let dictionary: UnboxableDictionary = [
"nested": [:]
]

do {
let model: Model = try Unbox(dictionary)

if let stringContext = model.nested.context as? String {
XCTAssertEqual(stringContext, "Context")
} else {
XCTFail("Unexpected context: \(model.nested.context)")
}
} catch {
XCTFail("Unexpected error: \(error)")
}
}

func testAccessingNestedDictionaryWithKeyPath() {
struct KeyPathModel: Unboxable {
Expand Down

0 comments on commit f8568ce

Please sign in to comment.