Created
November 14, 2011 02:19
-
-
Save akiellor/1363085 to your computer and use it in GitHub Desktop.
CommonJS implementation of Polyglot for Rhino.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var polyglot = require('polyglot'); | |
polyglot.register('coffee', require('coffee-script').CoffeeScript.compile); | |
polyglot.require('math').square(2); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.square = (x) -> x * x |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var compilers = {'js': function(source){return source;}}; | |
function register(ext, compile){ | |
compilers[ext] = compile; | |
} | |
function contents(lib){ | |
for(var ext in compilers){ | |
for(var index in require.paths){ | |
var f = new java.io.File(require.paths[index], lib + '.' + ext); | |
if(f.exists()){ | |
return compilers[ext](readFile(f.path)); | |
}else{ | |
continue; | |
} | |
} | |
} | |
throw "Module not found: " + lib; | |
} | |
function sandbox(){ | |
var ctx = Packages.org.mozilla.javascript.Context.enter(); | |
var scope = ctx.initStandardObjects(); | |
ctx.evaluateString(scope, "var exports = {};", "sandbox", 1, null); | |
return scope; | |
} | |
function req(lib){ | |
var ctx = Packages.org.mozilla.javascript.Context.enter(); | |
var scope = sandbox(); | |
ctx.evaluateString(scope, contents(lib), lib, 0, null); | |
return ctx.evaluateString(scope, "exports", "exports", 0, null); | |
} | |
exports.require = req; | |
exports.register = register; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment