Skip to content

Instantly share code, notes, and snippets.

@javierfs89
Created June 9, 2014 11:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javierfs89/eca13fa3429af26b9ac9 to your computer and use it in GitHub Desktop.
Save javierfs89/eca13fa3429af26b9ac9 to your computer and use it in GitHub Desktop.
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