Skip to content

Commit

Permalink
Merge pull request #466 from EB-Forks/feat/set-function-name
Browse files Browse the repository at this point in the history
feat: Set compiled function name
  • Loading branch information
mde committed Oct 30, 2019
2 parents c600a78 + ef38def commit 12a7541
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/ejs.js
Expand Up @@ -666,15 +666,10 @@ Template.prototype = {
throw e;
}

if (opts.client) {
fn.dependencies = this.dependencies;
return fn;
}

// Return a callable function which will execute the function
// created by the source-code, with the passed data as locals
// Adds a local `include` function which allows full recursive include
var returnedFn = function (data) {
var returnedFn = opts.client ? fn : function anonymous(data) {
var include = function (path, includeData) {
var d = utils.shallowCopy({}, data);
if (includeData) {
Expand All @@ -685,6 +680,18 @@ Template.prototype = {
return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
};
returnedFn.dependencies = this.dependencies;
if (opts.filename && typeof Object.defineProperty === 'function') {
var filename = opts.filename;
var basename = path.basename(filename, path.extname(filename));
try {
Object.defineProperty(returnedFn, 'name', {
value: basename,
writable: false,
enumerable: false,
configurable: true
});
} catch (e) {/* ignore */}
}
return returnedFn;
},

Expand Down
18 changes: 18 additions & 0 deletions test/ejs.js
Expand Up @@ -209,6 +209,24 @@ suite('ejs.compile(str, options)', function () {
}
throw new Error('no error reported when there should be');
});

var testFuncName = typeof Object.defineProperty === 'function' ? test : test.skip;

testFuncName('Compiled function name matches `filename` without the extension', function (done) {
var func = ejs.compile('<%= "Foo" %>', {
filename: 'foo.ejs'
});

assert.ok(func.name === 'foo');
return done();
});

testFuncName('Compiled function name defaults to "anonymous" when `filename` is unspecified', function (done) {
var func = ejs.compile('<%= "Foo" %>');

assert.ok(func.name === 'anonymous');
return done();
});
});

suite('client mode', function () {
Expand Down

0 comments on commit 12a7541

Please sign in to comment.