Skip to content

Instantly share code, notes, and snippets.

@erwan
Last active December 22, 2017 12:06
Show Gist options
  • Save erwan/24a2d8e5c8b0aaca9b646734f371e3c0 to your computer and use it in GitHub Desktop.
Save erwan/24a2d8e5c8b0aaca9b646734f371e3c0 to your computer and use it in GitHub Desktop.
import enumeratum._
sealed trait Mode extends EnumEntry
@SwaggerEnum
object Mode extends Enum[Mode] {
override def values = findValues
case object Initial extends Mode
case object Initial extends Mode
}
@ApiModel
case class Foobar(
@ApiModelProperty(dataType = "string", allowableValues = Mode.swaggerValues)
mode: Mode
)
package com.zendesk.walmart
import scala.meta._
import scala.annotation.StaticAnnotation
import scala.collection.immutable.Seq
abstract class SwaggerEnum extends StaticAnnotation {
inline def apply(defn: Any): Any = meta {
defn match {
case q"object $name extends ..$parents { ..$body }" => {
SwaggerEnumMacros.expandEnum(name, parents, body)
}
case _ => {
abort("must annotate an object.")
}
}
}
}
object SwaggerEnumMacros {
def expandEnum(name: Term.Name, parents: Seq[Ctor.Call], body: Seq[Stat]): Defn = {
val q"$pname[..$ptargs](...$pargss)" = parents match {
case head :: Nil => head
case _ => abort("Must annotate an Enum[A]")
}
val values = body.collect {
case q"$mods object $name extends ..$parents" => name
}
val reference = Lit.String(values.map(_.value).sorted.mkString(","))
q"""object $name extends ..$parents {
final val swaggerValues = $reference
..$body
}"""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment