Permalink
Browse files

Merge pull request #5 from txus/feature/hooks

Implement a basic hooks system
  • Loading branch information...
2 parents c6cbf05 + edb7672 commit 73847f969e631403460d74af34bde3b85ff73b5f @agnoster agnoster committed Aug 14, 2012
Showing with 30 additions and 1 deletion.
  1. +21 −1 lib/index.js
  2. +3 −0 package.json
  3. +6 −0 test/test.js
View
22 lib/index.js
@@ -1,4 +1,5 @@
var assert = require('assert')
+var sugar = require('sugar')
var captureRE = /\[([A-Za-z_][A-Za-z_0-9]*)\]/g
@@ -13,6 +14,23 @@ function mergeCaptures(current, next, noOverwrite) {
return current
}
+var Hooks = {
+ date: function(input) {
+ return Date.create(input).format('{yyyy}-{MM}-{dd}T{hh}:{mm}:{ss}{zzzz}');
+ }
+}
+
+function processHooks(input, hooks) {
+ var keys = Object.keys(hooks)
+
+ return keys.reduce(function(str, key) {
+ var regex = new RegExp("<" + key + ": ?([^>]+)>")
+ return str.replace(regex, function(_, match) {
+ return '"' + hooks[key](match) + '"'
+ })
+ }, input)
+}
+
function JSONExp(src, options) {
var self = function() {
return self.exec.apply(self, arguments)
@@ -68,14 +86,16 @@ function escapeString(match, contents) {
}
JSONExp.preprocess = function(src) {
- return src
+ var output = src
.replace(/"(.*?[^\\])"/g, escapeString)
.replace(/\.\.\.\s*\]/g, '{ "' + specials.many + '": true }]')
.replace(/\[\s*\.\.\./g, '[{ "' + specials.many + '": true }')
.replace(/\*/g, '{ "' + specials.any + '": true }')
.replace(/\.\.\./g, '"' + specials.glob + '": true')
.replace(captureRE, '{ "' + specials.capture + '": "$1" }')
.replace(/\s\/\/.*\n/, '')
+
+ return processHooks(output, Hooks);
}
JSONExp.parse = function(src) {
View
3 package.json
@@ -15,6 +15,9 @@
"pattern",
"match"
],
+ "dependencies": {
+ "sugar": "~1.3.0"
+ },
"devDependencies": {
"vows": "*"
},
View
6 test/test.js
@@ -1,6 +1,7 @@
var JSONExp = require('../lib/')
, vows = require('vows')
, assert = require('assert')
+ , sugar = require('sugar')
function test(src, pattern, cases) {
var batch = {}
@@ -82,6 +83,11 @@ vows.describe('JSONExp')
, '[1, 0, 2]': null
}
))
+.addBatch(test(
+ '{ "foo": <date: 1 month ago> }', {
+ foo: Date.create('1 month ago').format('{yyyy}-{MM}-{dd}T{hh}:{mm}:{ss}{zzzz}')
+ }
+))
.export(module)

0 comments on commit 73847f9

Please sign in to comment.