Created
December 4, 2009 03:46
-
-
Save nraychaudhuri/248807 to your computer and use it in GitHub Desktop.
This file contains 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
trait InterpolationContext { | |
implicit def str2interp(s: String) = new InterpolatedString(s) | |
class InterpolatedString(val s: String) { | |
def / = interpolate(s) | |
def identifier = s.substring(2, s.length - 1) | |
} | |
object Tokenizer { | |
def unapply(s: String): Option[Iterator[String]] = { | |
Some("\\$\\{.+?\\}".r.findAllIn(s).matchData.map { (x) => x.matched }) | |
} | |
} | |
def interpolate(s: String) = { | |
var sb = s | |
def evaluate(token:String):String = { | |
try { | |
val method = this.getClass.getMethod(token.identifier) | |
method.invoke(this).toString | |
} catch { | |
case _: NoSuchMethodException => token | |
} | |
} | |
s match { | |
case Tokenizer(tokens) => tokens.foreach { (x:String) => sb = sb.replace(x, evaluate(x)) } | |
} | |
sb | |
} | |
} | |
object Test extends InterpolationContext { | |
val a = "3" | |
def main(args: Array[String]) { | |
println("expanded: ${a}; not expanded: ${b}; more text"/) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment