2013-10-27 41 views
0

在斯卡拉播放框架2項目的看法,我想逐字顯示的源代碼片段是這樣的:評估在遊戲框架2模板Scala代碼字符串

@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

首先,一個免責聲明,我真的希望你能理解你打開了一個什麼樣的蠕蟲,可以使用類似js的eval並且你已經仔細考慮過了。 :)

我在一個小的小項目,我確實能夠評估Deck.js演示中Scala代碼重用斯卡拉控制檯,這是代碼,應該可以幫助您找出做的一個方式它(恐怕我不能完全回憶類加載器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") 
} 
+0

我該如何在Play 2視圖中使用此代碼? –

+0

你可以像模板中的任何Scala代碼那樣調用它。假設你把它放在@ some.package.SomeObject.eval(source)中,或者先用@import語句將它導入到作用域中。 – johanandren

+0

我想我想出了你的意圖。還有一個問題,所以我做了一個要點https://gist.github.com/mslinn/7205854 –