Skip to content

Instantly share code, notes, and snippets.

@yunnysunny
Forked from gavinengel/magic-globals.js
Created April 25, 2014 11:06
Show Gist options
  • Save yunnysunny/11285742 to your computer and use it in GitHub Desktop.
Save yunnysunny/11285742 to your computer and use it in GitHub Desktop.
// sets globals __line, __file, __ext, __dir
// copied and tweaked from: http://goo.gl/wwjGVV and http://goo.gl/umq4s1
// todo: __function and __method?
// begin setting magic properties into global
Object.defineProperty(global, '__stack', {
get: function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});
/**
* returns line number when placing this in your code: __line
*/
Object.defineProperty(global, '__line', {
get: function(){
return __stack[1].getLineNumber();
}
});
/**
* return filename (without directory path or file extension) when placing this in your code: __file
*/
Object.defineProperty(global, '__file', {
get: function(){
return __stack[1].getFileName().split('/').slice(-1)[0].split('.').slice(0)[0];
}
});
/**
* return file extension (without preceding period) when placing this in your code: __ext
*/
Object.defineProperty(global, '__ext', {
get: function(){
return __stack[1].getFileName().split('.').slice(-1)[0];
}
});
/**
* return path to filename (with trailing slash) when placing this in your code: __dir
*/
Object.defineProperty(global, '__dir', {
get: function(){
filename = __stack[1].getFileName().split('/').slice(-1)[0];
return __stack[1].getFileName().split(filename).slice(0)[0];
}
});
// end setting magic properties into global
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment