@@ -11,34 +11,41 @@ import PerfectLib
1111public class JSONConfig {
1212 public static let shared = JSONConfig ( )
1313 private var json : [ String : Any ] ?
14- public var source : String ? {
15- didSet {
16- if self . source != oldValue {
17- self . json = nil
18-
19- guard let source = self . source else { return }
20- let file = File ( source)
21- do {
22- try file. open ( . read, permissions: . readUser)
23- defer {
24- file. close ( )
25- }
26-
27- let text = try file. readString ( )
28- self . json = try text. jsonDecode ( ) as? [ String : Any ]
29-
30- } catch {
31- print ( " JSONConfig error: " + error. localizedDescription)
14+
15+ /// initialze the configuration with json at source. The json is first populated by the json at defaults (if it exists)
16+ public func initialize( withJsonAt source: String , defaultsInJsonAt defaults: String ? = nil ) {
17+ self . json = nil
18+ if let defaults = defaults {
19+ self . read ( jsonAt: defaults)
20+ }
21+ self . read ( jsonAt: source)
22+ }
23+
24+ private func read( jsonAt path: String ) {
25+ let file = File ( path)
26+ do {
27+ try file. open ( . read, permissions: . readUser)
28+ defer {
29+ file. close ( )
30+ }
31+
32+ let text = try file. readString ( )
33+ let dict = try text. jsonDecode ( ) as? [ String : Any ]
34+ if nil == self . json {
35+ self . json = dict
36+ }
37+ else if let dict = dict {
38+ for (k, v) in dict {
39+ self . json ? [ k] = v
3240 }
3341 }
42+
43+ } catch {
44+ print ( " JSONConfig error: " + error. localizedDescription)
3445 }
46+
3547 }
36-
37- private convenience init ( _ json: [ String : Any ] ? ) {
38- self . init ( )
39- self . json = json
40- }
41-
48+
4249 public func value( forKey key: String ) -> Any ? {
4350 guard let json = self . json else { return nil }
4451 return json [ key]
0 commit comments