Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
StripMargin string interpolator macro
/**
* This interpolator can be evaluated in compile time, so you can use to generate
* constant strings (if all params are also constant)
*
* Works on Scala 2.10.2
*/
implicit class stripInterpolator(sc: StringContext) {
def strip(params: Any*) = macro stripMacro
}
def stripMacro(c: Context)(params: c.Expr[Any]*): c.Expr[String] = {
import c.universe._
val Apply(_, List(Apply(_, rawParts))) = c.prefix.tree
val parts = rawParts.map(x => {
val Literal(Constant(res: String)) = x
res
})
val evalParams = params.map(x => {
c.eval(c.Expr[Any](c.resetAllAttrs(x.tree)))
})
val res = StringContext(parts:_*).s(evalParams:_*)
c.Expr[String](Literal(Constant(res.stripMargin)))
}
// scala> val name = "Foo"
// name: String = Foo
//
// scala> val email = "bar@baz.com"
// email: String = bar@baz.com
//
// scala> strip"""|{
// | "name" : "$name",
// | "email" : "$email"
// |}"""
//
// res0: String =
// {
// "name" : "Foo",
// "email" : "bar@baz.com"
// }
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment