Skip to content

Instantly share code, notes, and snippets.

@t3hnar
Created October 5, 2011 12:32
Show Gist options
  • Save t3hnar/1264323 to your computer and use it in GitHub Desktop.
Save t3hnar/1264323 to your computer and use it in GitHub Desktop.
Squeryl Entity
package org.squeryl
import annotations.Transient
import java.lang.reflect.Field
/**
* @author Yaroslav Klymko
*/
trait HasValues {
protected def values: List[Any]
}
trait EquateValues extends Equals with HasValues {
override def hashCode() = values.hashCode()
override def equals(a: Any) = a match {
case that: EquateValues if this.canEqual(that) && that.canEqual(this) =>
this.values == that.values
case _ => false
}
def canEqual(that: Any): Boolean = that.getClass.isAssignableFrom(getClass)
}
trait ValuesToString {
self: HasValues =>
override def toString = getClass.getSimpleName + "(" + valuesToString + ")"
protected def valuesToString: String = {
val fs: List[(String, Any)] = _fields.map(field => field.getName -> field.get(this))
fs.map {
case (name, Some(value)) => name + "=" + value
case (name, value) => name + "=" + value
}.mkString(", ")
}
@Transient
private lazy val _fields: List[Field] = {
def get(clazz: Class[_]): List[Field] = if (clazz != classOf[Object]) {
get(clazz.getSuperclass) ::: clazz.getDeclaredFields.toList
} else Nil
val fs: List[(Field, Any)] = get(getClass).map {
f =>
f.setAccessible(true)
f -> f.get(this)
}
values flatMap (value => fs.find(_._2 == value).map(_._1))
}
}
trait Entity extends HasValues with EquateValues with ValuesToString
class Point(val x: Int, val y: Int) extends Entity {
def values = List(x, y)
}
val x = new Point(1, 2)
val x2 = new Point(1, 2)
x == x2 // true
x.toString //Point(x=1, y=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment