Is there a way to generate a method within a particular class/trait/object based on TypesafeConfig object at compile time?
For instance, I have this:
object Main {
val config: Config = ConfigFactory.parseString(
"""
|object {
| name = "go"
|}
""".stripMargin)
generate(config)
}
And the expected result is:
object Main {
val config: Config = ConfigFactory.parseString(
"""
|object {
| name = "go"
|}
""".stripMargin)
def method: Unit = {
print("go") /* the string comes from the config above */
}
}
The idea is to be able to instantiate the Config object within the scope of macro implementation and use its properties to generate the code, e.g. (many thanks to Dmytro Minin for the example):
object GenerateMacro {
def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
import c.universe._
confObj = ... /* somehow get the real object based on macro input */
annottees match {
case q"$mods object $tname extends { ..$earlydefns } with ..$parents { $self => ..$body }" :: Nil =>
q"""$mods object $tname extends { ..$earlydefns } with ..$parents { $self =>
..$body
def method: Unit = {
print(s"${confObj.getString("object.name")}") /* use confObj's property to "embed" the value into the method generated */
}
}"""
}
}
}