Skip to content

Instantly share code, notes, and snippets.

@akiellor
Created November 14, 2011 02:19
Show Gist options
  • Save akiellor/1363085 to your computer and use it in GitHub Desktop.
Save akiellor/1363085 to your computer and use it in GitHub Desktop.
CommonJS implementation of Polyglot for Rhino.
var polyglot = require('polyglot');
polyglot.register('coffee', require('coffee-script').CoffeeScript.compile);
polyglot.require('math').square(2);
exports.square = (x) -> x * x
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