Skip to content

Instantly share code, notes, and snippets.

@nraychaudhuri
Created December 4, 2009 03:46
Show Gist options
  • Save nraychaudhuri/248807 to your computer and use it in GitHub Desktop.
Save nraychaudhuri/248807 to your computer and use it in GitHub Desktop.
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