Skip to content

Instantly share code, notes, and snippets.

@SammyVimes
Last active January 27, 2017 14:41
Show Gist options
  • Save SammyVimes/f291bee0ad5e2e733ef676f8383adfc1 to your computer and use it in GitHub Desktop.
Save SammyVimes/f291bee0ad5e2e733ef676f8383adfc1 to your computer and use it in GitHub Desktop.
GlossyModelGenerator for swift
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