Last active
January 27, 2017 14:41
-
-
Save SammyVimes/f291bee0ad5e2e733ef676f8383adfc1 to your computer and use it in GitHub Desktop.
GlossyModelGenerator for swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
glossGenerator("CLChatFile", { | |
id: "Int64", | |
regDate: "Date", | |
ownerId: "Int64?", | |
filename: "String", | |
mimeType: "String", | |
length: "Int64", | |
md5: "String" | |
}) | |
function glossGenerator(className, fields) { | |
var res = "class " + className + ": Glossy {\n\n"; | |
let keys = Object.keys(fields); | |
let ctor = "\trequired init?(json: JSON) {\n"; | |
let hasGuard = false; | |
let guarded = []; | |
let guardedExpr = ""; | |
let notGuardedExpr = ""; | |
keys.map(function (key) { | |
let type = fields[key]; | |
res += "\tlet " + key + ": " + type + "\n"; | |
if (!type.endsWith("?")) { | |
if (!hasGuard) { | |
guardedExpr += '\t\tguard ' | |
hasGuard = true; | |
} else { | |
guardedExpr += ',\n\t\t\t'; | |
} | |
guardedExpr += 'let ' + key + ': ' + type + ' = "' + key + '" <~~ json' | |
guarded.push(key); | |
notGuardedExpr += "\t\tself." + key + " = " + key + "\n"; | |
} else { | |
notGuardedExpr += "\t\tself." + key + " = " + '("' + key + '" <~~ json)' + "\n"; | |
} | |
}); | |
ctor += guardedExpr + "\n\t\telse {\n\t\t\treturn nil\n\t\t}\n"; | |
ctor += notGuardedExpr; | |
ctor += "\n\t}\n\n"; | |
res += "\n" + ctor; | |
res += "\tfunc toJSON() -> JSON? {\n"; | |
res += "\t\treturn jsonify([\n" | |
keys.map(function (key) { | |
res += '\t\t\t"' + key + '" ~~> self.' + key + ',\n' | |
}); | |
res += "\t\t])\n\t}\n\n" | |
res += "}" | |
console.log(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment