Skip to content

Instantly share code, notes, and snippets.

@teamon
Created April 17, 2010 22:01
Show Gist options
  • Save teamon/369834 to your computer and use it in GitHub Desktop.
Save teamon/369834 to your computer and use it in GitHub Desktop.
class ScalaModel[T] {
def valid_? = {
errors.clear
validate
errors.empty_?
}
def validate {}
def req(field: String, fun: => Boolean, msg: String){
if(!fun) errors.add(field, msg)
}
object errors {
val fields = Map[String, ListBuffer[String]]()
def clear = fields.clear
def empty_? = fields.isEmpty
def add(field: String, msg: String){
if(!fields.contains(field)){
fields(field) = new ListBuffer[String]
}
fields(field) += msg
}
def full = fields.values.toList.flatten
}
}
scala> val u = new User
u: models.User = models.User@9c98e8
scala> u.valid_?
res12: Boolean = false
scala> u.errors.full
res14: List[String] = List(Underage!, Username is too short)
scala> u.username = "foobarbaz"
scala> u.valid_?
res15: Boolean = false
scala> u.errors.full
res16: List[String] = List(Underage!)
scala> u.age = 30
scala> u.valid_?
res17: Boolean = true
scala> u.errors.full
res18: List[String] = List()
class User extends ScalaModel {
var username: String = ""
var age: Int = 0
override def validate {
req("username", username.length > 6, "Username is too short")
req("age", age > 18, "Underage!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment