Skip to content

Instantly share code, notes, and snippets.

@joan38
Last active August 29, 2015 14:08
Show Gist options
  • Save joan38/a95877c8c776a6db42b1 to your computer and use it in GitHub Desktop.
Save joan38/a95877c8c776a6db42b1 to your computer and use it in GitHub Desktop.
Gremlin vertex to case class and case class saver
package gremlin.scala.caseclass
import com.tinkerpop.gremlin.scala._
import com.tinkerpop.gremlin.structure.Vertex
import shapeless.HList
import scala.reflect._
import scala.reflect.runtime.universe._
/**
* Created by Joan on 24/10/2014.
*/
object CaseClassWrapper {
implicit class ScalaGraphCaseClass(graph: ScalaGraph) {
def saveCC[A: TypeTag: ClassTag](cc: A) = {
val mirror = runtimeMirror(cc.getClass.getClassLoader)
val instanceMirror = mirror.reflect(cc)
val params = (typeOf[A].declarations map (_.asTerm) filter (_.isGetter) map { term =>
val fieldMirror = instanceMirror.reflectField(term)
term.name.decoded -> (term.typeSignature.typeSymbol.fullName match {
case t if t == typeOf[Option[_]].typeSymbol.fullName =>
fieldMirror.get.asInstanceOf[Option[Any]].getOrElse(null)
case _ => fieldMirror.get
})
} filter (_._1 != "id")).toMap + ("label" -> cc.getClass.getSimpleName)
graph.addVertex().setProperties(params)
}
}
implicit class GremlinScalaCaseClass[End <: Vertex, Labels <: HList](gs: GremlinScala[End, Labels]) {
def toCC[A: TypeTag] = gs.map[A] { vertex =>
val mirror = runtimeMirror(getClass.getClassLoader)
val classA = typeOf[A].typeSymbol.asClass
val classMirror = mirror.reflectClass(classA)
val constructor = typeOf[A].declaration(nme.CONSTRUCTOR).asMethod
val params = constructor.paramss.head map {
case field if field.name.decoded == "id" => vertex.id.toString
case field if field.typeSignature.typeSymbol.fullName == typeOf[Option[_]].typeSymbol.fullName =>
Option(vertex.valueOrElse(field.name.decoded, null))
case field => vertex.valueOrElse(field.name.decoded, null)
}
val constructorMirror = classMirror.reflectConstructor(constructor)
constructorMirror(params: _*).asInstanceOf[A]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment