Last active
February 12, 2016 20:33
-
-
Save ASRagab/679e04086216b543d04c to your computer and use it in GitHub Desktop.
This file contains 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
trait Database[S, T] { | |
def objectsFrom[U <: Option[Seq[S]]](action: U)(implicit toDTO: S => T) : Option[Seq[T]] = { | |
action match { | |
case Some(result) => Some(result.map(toDTO)) | |
case None => Some(Seq.empty) | |
} | |
} | |
def rowsFrom[V <: Option[Seq[T]]](action: V)(implicit toDAO: T => S) : Option[Seq[S]] = { | |
action match { | |
case Some(result) => Some(result.map(toDAO)) | |
case None => Some(Seq.empty) | |
} | |
} | |
} | |
sealed trait DO | |
trait DAO extends DO | |
trait DTO extends DO | |
object ThingRunner { | |
case class ThingDAO(id: Int, name: String) extends DAO | |
case class ThingDTO(id: Int, name: String) extends DTO | |
object ThingDTO { | |
def convertFromRow(row: ThingDAO): ThingDTO = ThingDTO(row.id, row.name) | |
def convertToRow(o: ThingDTO): ThingDAO = ThingDAO(o.id, o.name) | |
} | |
implicit object ThingDatabase extends Database[ThingDAO, ThingDTO] | |
implicit val toDTO: ThingDAO => ThingDTO = ThingDTO.convertFromRow | |
implicit val toDAO: ThingDTO => ThingDAO = ThingDTO.convertToRow | |
val rows = Some(Seq(ThingDAO(10, "10"), ThingDAO(2, "2"))) | |
var objects = Some(Seq(ThingDTO(100, "100"), ThingDTO(1000, "1000"))) | |
val dtoList = ThingDatabase objectsFrom rows | |
val daoList = ThingDatabase rowsFrom objects | |
} | |
object OtherThingRunner { | |
case class OtherThingDAO(size: Float, day: Option[String]) extends DAO | |
case class OtherThingDTO(size: Float, day: Option[String]) extends DTO | |
object converter { | |
def convertFromRow(row: OtherThingDAO): OtherThingDTO = OtherThingDTO(row.size, row.day) | |
def convertToRow(o: OtherThingDTO): OtherThingDAO = OtherThingDAO(o.size, o.day) | |
} | |
implicit object ThingDatabase extends Database[OtherThingDAO, OtherThingDTO] | |
implicit val toDTO: OtherThingDAO => OtherThingDTO = converter.convertFromRow | |
implicit val toDAO: OtherThingDTO => OtherThingDAO = converter.convertToRow | |
val rows = Some(Seq(OtherThingDAO(10.0F, Some("Monday")), OtherThingDAO(2.0F, None))) | |
var objects = Some(Seq(OtherThingDTO(100.0F, Some("Tuesday")), OtherThingDTO(1000F, Some("Friday")))) | |
val dtoList = ThingDatabase objectsFrom rows | |
val daoList = ThingDatabase rowsFrom objects | |
} | |
ThingRunner.daoList | |
ThingRunner.dtoList | |
OtherThingRunner.daoList | |
OtherThingRunner.dtoList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment