1
0

Card.scala 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package models
  2. import anorm._
  3. import anorm.SqlParser._
  4. import play.api.db._
  5. import play.api.libs.json._
  6. import play.api.Play.current
  7. object Card {
  8. implicit val writes = new Writes[Card] {
  9. def writes(o: Card) = Json.obj(
  10. "word" -> o.word,
  11. "taboo" -> o.taboo
  12. )
  13. }
  14. def add(card: Card) = DB.withTransaction { implicit c =>
  15. val id = SQL("insert into words values (default, {word})")
  16. .on('word -> card.word)
  17. .executeInsert()
  18. id.map { id =>
  19. card.taboo.map { word =>
  20. SQL("insert into taboo values (default, {id}, {word})")
  21. .on('id -> id, 'word -> word)
  22. .executeInsert()
  23. }
  24. }
  25. }
  26. def getRandom() = DB.withConnection { implicit c =>
  27. SQL("""
  28. with rand as (
  29. select * from words offset random() * (select count(*) from words) limit 1
  30. )
  31. select rand.word as word, taboo.word as taboo from taboo, rand where word_id = rand.id
  32. """)
  33. .list(str("word") ~ str("taboo") map flatten)
  34. .groupBy(_._1)
  35. .map { case (word, taboos) => Card(word, taboos.map(_._2).toSet) }
  36. .head
  37. }
  38. }
  39. case class Card(word: String, taboo: Set[String]) {
  40. def isTaboo(text: String) = {
  41. val lower = text.toLowerCase
  42. def contains(word: String) = {
  43. lower.indexOf(word.toLowerCase) >= 0
  44. }
  45. // check if text contains word or anything in taboo
  46. (taboo + word).map(contains).foldLeft(false)(_ || _)
  47. }
  48. def isCorrect(text: String) = {
  49. text.toLowerCase.indexOf(word.toLowerCase) >= 0
  50. }
  51. }