Skip to content

Instantly share code, notes, and snippets.

@potench
Last active December 10, 2015 19:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potench/4480385 to your computer and use it in GitHub Desktop.
Save potench/4480385 to your computer and use it in GitHub Desktop.
Creating a Model using a grunt task
// Save to: `robyn/tasks/model.js`
// Run with: `grunt model:NameofModel`
module.exports = function (grunt) {
var requirejs = require('requirejs'),
fs = require("fs"),
wrench = require("wrench"),
path = require("path"),
scope = path.join("project", "static", "js"),
project = path.join(scope, grunt.task.directive("<config:meta.projectName>"));
grunt.registerTask("model", "Makes a new model", function (modelName) {
var done = this.async(),
hasErrors = false;
requirejs.config({
nodeRequire: require,
baseUrl : scope
});
requirejs(
[
"./rosy/base/Class"
], function (Class) {
var GenerateModel = Class.extend({
init : function () {
if (modelName) {
this.writeModel();
} else {
console.log("Please supply a model-name!".red);
hasErrors = true;
done(!hasErrors);
}
},
writeModel : function () {
var models = path.join(project, "models"), // TODOS: make default folder "models" but allow user to change this folder
output = path.join(models, this.capitalize(modelName) + ".js"),
msg = 'define(\n\t[\n\t\t"rosy/base/Model"\n\t],\n\tfunction (Model) {\n\n\t\t"use strict";\n\n\t\t// This is a bit redundant at the moment, but it\n\t\t// will also provide flexibility if the model ever\n\t\t// needs to do anything special.\n\t\treturn Model.extend({});\n\n\t}\n);';
// make sure the models dir exists
wrench.mkdirSyncRecursive(models);
// create a file with Model formatting
fs.writeFile(output, msg, function(err) {
if (err) {
console.log("Error writing file: " + err.red);
isSuccessful = false;
} else {
var msg = "[Wrote to: " + output + "]"
console.log(msg.yellow);
}
done(!hasErrors);
});
},
capitalize : function (str) {
return str[0].toUpperCase() + str.slice(1);
}
});
return new GenerateModel();
}
);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment