Skip to content

Make Path Codable #91

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions Sources/Path+Extensions.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import Foundation

extension Path: Codable {
public init?(_ string: String?) {
guard let string = string else { return nil }
self.init(string)
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(string)
}

public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string: String = try container.decode(String.self)
self.init(string)
}
}
33 changes: 33 additions & 0 deletions Tests/PathKitTests/XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,37 @@ class PathKitTests: XCTestCase {
func testRunSpectre() {
testPathKit()
}

func test_codable() throws {
// GIVEN
let path: Path = .init("/testPath")
let encoder: JSONEncoder = .init()
let decoder: JSONDecoder = .init()

// WHEN
let data: Data = try encoder.encode(path)
let decodedPath: Path = try decoder.decode(Path.self, from: data)

// THEN
XCTAssertEqual(path, decodedPath)
}

func test_init_string() {
// GIVEN
let path: Path = .init("/testPath")

// WHEN
let initPath: Path = .init(path.string)

// THEN
XCTAssertEqual(path, initPath)
}

func test_init_nil() {
// WHEN
let initPath: Path? = .init(nil)

// THEN
XCTAssertNil(initPath)
}
}