在Scala Play Framework 2项目的视图中,我希望逐字显示一段源代码:
@if(true) { "The world has ended!" }
随后是编译结果:
"The world has ended!"
我想通过定义一个接受包含该代码段的String
的方法来实现这一点,并输出两个版本,如下所示:
@sideBySide(content: String) = {
content -> eval(content)
}
我会这样称呼:
@sideBySide("""@if(false) { "The world has ended!" }""")
所以问题是如何写eval
。
答案 0 :(得分:0)
首先,一个免责声明,我真的希望你能通过提供类似js的eval来了解你打开了什么样的蠕虫,并且你已经仔细考虑了这一点。 :)
我在一个小项目中重用了Scala Console,以便能够在Deck.js演示文稿中评估Scala代码,这是代码,应该帮助您弄清楚一个方式这样做(我恐怕不能完全回想起classloader trixery背后的理由):
val settings: Settings = {
lazy val urls = java.lang.Thread.currentThread.getContextClassLoader match {
case cl: java.net.URLClassLoader => cl.getURLs.toList
case _ => sys.error("classloader is not a URLClassLoader")
}
lazy val classpath = urls map {_.toString}
val tmp = new Settings()
tmp.bootclasspath.value = classpath.distinct mkString File.pathSeparator
tmp
}
val interpreter = new IMain(settings)
def unsafeEval(source: String): String =
stringFromStream { sout =>
Console.withOut(sout) {
interpreter.interpret(source)
}
}
// lets someone write to a stream and then we return the string contents of that stream
def stringFromStream(f: (OutputStream) => Any): String = {
val out = new ByteArrayOutputStream
f(out)
out.toString("UTF-8")
}