Skip to content

Instantly share code, notes, and snippets.

@emenegro
Created March 21, 2017 19:19
Show Gist options
  • Save emenegro/b647162dfebd0c1bb4966baa0e7f469c to your computer and use it in GitHub Desktop.
Save emenegro/b647162dfebd0c1bb4966baa0e7f469c to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
protocol OfflineRequestConvertible {}
extension String: OfflineRequestConvertible {}
struct OfflineAction {
enum `Type` {
case cache, get, delete
}
fileprivate(set) var type: Type?
fileprivate(set) var request: OfflineRequestConvertible?
fileprivate(set) var data: Data?
fileprivate(set) var id: String?
fileprivate(set) var encryptionKey: String?
fileprivate(set) var keepAliveUntil: Date?
fileprivate(set) var ifBefore: Date?
}
protocol BuildStep {
func build() -> OfflineAction
}
protocol RequestStep {
func toCache(_ request: OfflineRequestConvertible) -> DataStep
func toGet(_ request: OfflineRequestConvertible) -> GetCommonsStep
func toDelete(_ request: OfflineRequestConvertible) -> CommonsStep
}
protocol DataStep {
func data(_ data: Data) -> CacheCommonsStep
}
protocol CommonsStep: BuildStep {
func forId(_ id: String) -> Self
func withEncryptionKey(_ encryptionKey: String) -> Self
}
protocol CacheCommonsStep: CommonsStep {
func keepingAliveUntil(_ date: Date) -> Self
}
protocol GetCommonsStep: CommonsStep {
func ifBefore(_ date: Date) -> Self
}
class OfflineActionBuilder {
fileprivate var action: OfflineAction!
init() {
fatalError("This type cannot be constructed directly, use static var 'builder' instead.")
}
private init(_ action: OfflineAction) {
self.action = action
}
static var builder: RequestStep {
return OfflineActionBuilder(OfflineAction()) as RequestStep
}
}
extension OfflineActionBuilder: RequestStep, DataStep, CommonsStep, CacheCommonsStep, GetCommonsStep {
func toCache(_ request: OfflineRequestConvertible) -> DataStep {
action.type = .cache
action.request = request
return self as DataStep
}
func toGet(_ request: OfflineRequestConvertible) -> GetCommonsStep {
action.type = .get
action.request = request
return self as GetCommonsStep
}
func toDelete(_ request: OfflineRequestConvertible) -> CommonsStep {
action.type = .delete
action.request = request
return self as CommonsStep
}
func data(_ data: Data) -> CacheCommonsStep {
action.data = data
return self as CacheCommonsStep
}
func forId(_ id: String) -> Self {
action.id = id
return self
}
func withEncryptionKey(_ encryptionKey: String) -> Self {
action.encryptionKey = encryptionKey
return self
}
func keepingAliveUntil(_ date: Date) -> Self {
action.keepAliveUntil = date
return self
}
func ifBefore(_ date: Date) -> Self {
action.ifBefore = date
return self
}
func build() -> OfflineAction {
return action
}
}
// Let's build here:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment