Created
April 17, 2010 22:01
-
-
Save teamon/369834 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
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 | |
} | |
} |
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
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() |
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
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