Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 13:56
Show Gist options
  • Save dgageot/9021229 to your computer and use it in GitHub Desktop.
Save dgageot/9021229 to your computer and use it in GitHub Desktop.
import static java.nio.charset.StandardCharsets.*;
import static javax.script.ScriptContext.*;
import javax.script.*;
public class CoffeeToJs {
private final CompiledScript compiledScript;
private final Bindings bindings;
public CoffeeToJs() {
String script = readScript("META-INF/resources/webjars/coffee-script/1.7.0/coffee-script.min.js");
ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
try {
compiledScript = ((Compilable) nashorn).compile(script + "\nCoffeeScript.compile(__source, {bare: true});");
bindings = nashorn.getBindings(ENGINE_SCOPE);
} catch (ScriptException e) {
throw new RuntimeException("Unable to compile script", e);
private static String readScript(String path) {
try (InputStream input = ClassLoader.getSystemResourceAsStream(path)) {
return InputStreams.readString(input, UTF_8);
} catch (IOException e) {
throw new RuntimeException("Unable to read " + path, e);
public synchronized String toJs(String coffee) throws ScriptException {
bindings.put("__source", coffee);
return compiledScript.eval(bindings).toString();
import static org.assertj.core.api.Assertions.*;
import org.junit.*;
import javax.script.*;
public class CoffeeToJsTest {
static CoffeeToJs coffeeToJs = new CoffeeToJs();
public void empty() throws ScriptException {
String js = new CoffeeToJs().toJs("");
public void to_javascript() throws ScriptException {
String js = coffeeToJs.toJs("life=42");
assertThat(js).isEqualTo("var life;\n\nlife = 42;\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment