Last active
August 29, 2015 13:56
-
-
Save dgageot/9021229 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import static java.nio.charset.StandardCharsets.*; | |
import static javax.script.ScriptContext.*; | |
import java.io.*; | |
import net.codestory.http.io.*; | |
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(); | |
} | |
} |
This file contains hidden or 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
import static org.assertj.core.api.Assertions.*; | |
import java.io.*; | |
import org.junit.*; | |
import javax.script.*; | |
public class CoffeeToJsTest { | |
static CoffeeToJs coffeeToJs = new CoffeeToJs(); | |
@Test | |
public void empty() throws ScriptException { | |
String js = new CoffeeToJs().toJs(""); | |
assertThat(js).isEqualTo("\n"); | |
} | |
@Test | |
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