Skip to content

Instantly share code, notes, and snippets.

@madbook
Created July 27, 2013 05:19
Show Gist options
  • Save madbook/6093811 to your computer and use it in GitHub Desktop.
Save madbook/6093811 to your computer and use it in GitHub Desktop.
A contrived example of a function for templating javascript files in javascript. The `__compile__` function extracts the function body of a passed in anonymous function, then (optionally) replaces keywords (e.g., __foo__) with properties from a passed in object.
/**
* given a function, strips out its body code and optionally replaces
* template tags (variable names surrounded by double-underscores,
* e.g., __foo__) replacing them with values from a passed in object
*/
__compile__ = function (fnc, obj) {
var body = fnc.toString().match(/^function\s*[0-9a-zA-Z_$]*\s*\([\w\s,\$_]*\)\s*\{(?:\s*\n?)?([\w\W\s]*)\n?\}$/m)[1]
if (obj === undefined)
return body
var matches = body.match(/(__[0-9a-zA-Z_$]*__)+/gm)
var i = matches.length
var matchedKeys = {}
var key, key2
while (i-- > 0) {
key = matches[i]
if (key.length < 5 || typeof matchedKeys[key] !== 'undefined')
continue
key2 = key.substr(2, key.length - 4)
if (typeof obj[key2] === 'undefined')
throw 'Undefined replacement ' + key
matchedKeys[key] = key2
body = body.replace(new RegExp(key, 'g'), obj[key2])
}
return body
}
/**
* example use - defining a template, then rendering out a few copies of it
*/
var queryTemplate = function () {
exports.__method__ = function (req, res, next) {
var db = req.openMysqlConnection()
var sql = "__query__"
var params = [__params__]
db.query(sql, params, function(err, rows){
if (err) throw err
res.write(JSON.stringify(rows))
})
db.end(function(err){
if (err) throw err
res.end()
})
}
}
__compile__(queryTemplate, {
method: 'getFoo',
query: "SELECT * FROM foo WHERE id = ?",
params: 'req.body.id'
})
__compile__(queryTemplate, {
method: 'insertFoo',
query: "INSERT INTO foo SET bar = ? ",
params: 'req.body.bar'
})
__compile__(queryTemplate, {
method: 'updateFoo',
query: "UPDATE foo SET bar = ? WHERE id = ?",
params: 'req.body.bar, req.body.id'
})
__compile__(queryTemplate, {
method: 'deleteFoo',
query: "DELETE FROM foo WHERE id = ?",
params: 'req.body.id'
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment