Card.scala 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. val list = SQL("""
  28. with rand as (
  29. select * from words offset floor(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. mapToCard(list).head
  35. }
  36. def list() = DB.withConnection { implicit c =>
  37. val list = SQL("""
  38. select words.word as word, taboo.word as taboo
  39. from words left join taboo on word_id = words.id
  40. """)
  41. .list(str("word") ~ str("taboo") map flatten)
  42. mapToCard(list)
  43. }
  44. def mapToCard(seq: Seq[(String, String)]) = {
  45. seq.groupBy(_._1).map {
  46. case (word, taboos) => Card(word, taboos.map(_._2).toSet)
  47. }
  48. }
  49. }
  50. case class Card(word: String, taboo: Set[String]) {
  51. lazy val tabooRegex = (taboo + word).map { word =>
  52. ("\\b"+word.toLowerCase+"\\b").r
  53. }
  54. def isTaboo(text: String) = {
  55. val lower = text.toLowerCase
  56. // check if text contains word or anything in taboo
  57. tabooRegex.map(!_.findFirstIn(lower).isEmpty).foldLeft(false)(_ || _)
  58. }
  59. def isCorrect(text: String) = {
  60. text.toLowerCase.indexOf(word.toLowerCase) >= 0
  61. }
  62. }