Created
June 9, 2014 11:27
-
-
Save javierfs89/eca13fa3429af26b9ac9 to your computer and use it in GitHub Desktop.
StripMargin string interpolator macro
This file contains hidden or 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
/** | |
* 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 = "[email protected]" | |
// email: String = [email protected] | |
// | |
// scala> strip"""|{ | |
// | "name" : "$name", | |
// | "email" : "$email" | |
// |}""" | |
// | |
// res0: String = | |
// { | |
// "name" : "Foo", | |
// "email" : "[email protected]" | |
// } | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment