Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactiveMongo : How to write macros handler to Enumeration object?

I use ReactiveMongo 0.10.0, and I have following user case class and gender Enumeration object:

case class User(
                 _id: Option[BSONObjectID] = None,
                 name: String,
                 gender: Option[Gender.Gender] = None)

object Gender extends Enumeration {
  type Gender = Value
  val MALE = Value("male")
  val FEMALE = Value("female")
  val BOTH = Value("both")
}

And I declare two implicit macros handler:

implicit val genderHandler = Macros.handler[Gender.Gender]

implicit val userHandler = Macros.handler[User]

but, when I run application, I get following error:

Error:(123, 48) No apply function found for reactive.userservice.Gender.Gender
    implicit val genderHandler = Macros.handler[Gender.Gender]
                                               ^
Error:(125, 46) Implicit reactive.userservice.Gender.Gender for 'value gender' not found
    implicit val userHandler = Macros.handler[User]
                                         ^

Anybody know how to write macros handler to Enumeration object?

Thanks in advance!

like image 516
SBotirov Avatar asked Mar 18 '23 23:03

SBotirov


1 Answers

I stumbled upon your question a few times searching for the same answer. I did it this way:

import myproject.utils.EnumUtils
import play.api.libs.json.{Reads, Writes}
import reactivemongo.bson._

object DBExecutionStatus extends Enumeration {
  type DBExecutionStatus = Value

  val Error = Value("Error")
  val Started = Value("Success")
  val Created = Value("Running")

  implicit val enumReads: Reads[DBExecutionStatus] = EnumUtils.enumReads(DBExecutionStatus)

  implicit def enumWrites: Writes[DBExecutionStatus] = EnumUtils.enumWrites

  implicit object BSONEnumHandler extends BSONHandler[BSONString, DBExecutionStatus] {
    def read(doc: BSONString) = DBExecutionStatus.Value(doc.value)
    def write(stats: DBExecutionStatus) = BSON.write(stats.toString)
  }

}

You have to create a read/write pair by hand and populate with your values. Hope you already solved this issue given the question age :D

like image 171
rmredin Avatar answered Mar 21 '23 13:03

rmredin