forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlebars_helpers_loader.js
67 lines (60 loc) · 2.38 KB
/
handlebars_helpers_loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// handlebars-loader wants to know about every helper we have, and uses
// a file convention to autofind them. Since we don't match that
// convention, we need to specify which helpers are ones it should
// count on being present (ones defined in handlebars_helpers).
// We'll then make sure modules requiring a jst file have a dependency
// on handlebars_helpers built in, since they self-register with handlebars
//runtime that should be ok.
var fs = require('fs');
var path = require('path');
var coffee = require('coffee-script');
var loadHelpersAST = function(){
var filename = path.join(__dirname, "..", "app/coffeescripts/handlebars_helpers.coffee");
var source = fs.readFileSync(filename, 'utf8');
return coffee.nodes(source);
};
// we're looking in the helpers AST for the for loop that goes through a javascript
// object (the "source" object) and calls "registerHelper" with each property
// We want to make those same properties into "known" helpers.
var isHandlebarsAssignmentNode = function(node){
var result = node.body.contains(function(childNode){
return childNode.constructor.name === 'Call' &&
childNode.variable.base.value === 'Handlebars' &&
childNode.variable.contains(function(registerNode){
return registerNode.constructor.name === 'Access' &&
registerNode.name.value === 'registerHelper';
});
});
return result;
}
var findHelperNodes = function(helpersAST){
var helpersCollection = null;
helpersAST.traverseChildren(true, function(child){
if(child.constructor.name === 'For'){
if(isHandlebarsAssignmentNode(child)){
helpersCollection = child.source.base.properties;
return false;
}
}
});
return helpersCollection;
}
// given an array of nodes (which are functions assigned to property names),
// return an array of property names in the "knownHelpers" query format for
// the handlebars loader.
var buildQueryStringElements = function(helperNodes){
var queryElements = [];
helperNodes.forEach(function(helper){
var helperName = helper.variable.base.value;
queryElements.push("knownHelpers[]=" + helperName);
});
return queryElements;
};
module.exports = {
queryString: function(){
var helpersAST = loadHelpersAST();
var helpersCollection = findHelperNodes(helpersAST);
var queryElements = buildQueryStringElements(helpersCollection);
return queryElements.join("&");
}
}