PageRenderTime 40ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/app/models/Post.scala

http://github.com/leodagdag/persistance
Scala | 76 lines | 64 code | 12 blank | 0 comment | 5 complexity | 755096b19628753c5f34242f756ccbf2 MD5 | raw file
  1. package models
  2. import _root_.plugin._
  3. import com.novus.salat.dao._
  4. import com.mongodb.casbah.Imports._
  5. import controllers.Blog
  6. import javax.persistence.EntityNotFoundException
  7. import org.joda.time.DateTime
  8. import play.api.libs.json.Json._
  9. import play.api.libs.json.{JsObject, JsString, JsValue, Writes}
  10. case class Post(_id: ObjectId = new ObjectId,
  11. title: String,
  12. content: String,
  13. featured: Boolean = false,
  14. authorId: Option[ObjectId] = None,
  15. created: DateTime = new DateTime(),
  16. var comments: List[Comment] = Nil) {
  17. def simpleCopy(src: Post): Post = {
  18. this.copy(title = src.title,
  19. content = src.content,
  20. featured = src.featured)
  21. }
  22. }
  23. object Post extends SalatDAO[Post, ObjectId](collection = DB.connection("Post")) with Model[Post, ObjectId] with Writes[Post] {
  24. com.mongodb.casbah.commons.conversions.scala.RegisterConversionHelpers()
  25. com.mongodb.casbah.commons.conversions.scala.RegisterJodaTimeConversionHelpers()
  26. def writes(post: Post): JsValue = JsObject(
  27. List(
  28. "_id" -> JsString(post._id.toString),
  29. "title" -> toJson(post.title),
  30. "content" -> toJson(post.content),
  31. "created" -> toJson(post.created.toDate.getTime),
  32. "featured" -> toJson(post.featured)
  33. ))
  34. override val PAGE_SIZE = Blog.config.getInt("pageSize").getOrElse(10)
  35. def addComment(id: ObjectId, comment: Comment) {
  36. val post = this.findOneByID(id)
  37. post match {
  38. case Some(post) =>
  39. if (post.comments == null) {
  40. post.comments = List(comment)
  41. } else {
  42. post.comments = post.comments.+:(comment)
  43. }
  44. this.save(post)
  45. case _ => throw new EntityNotFoundException("Problem retrieving a post with id[%s]".format(id))
  46. }
  47. }
  48. def featured: Option[Post] = Post.findOne(MongoDBObject("featured" -> true))
  49. override def update[A <: DBObject](q: A, post: Post)(implicit dao: SalatDAO[Post, ObjectId]) {
  50. if (post.featured) {
  51. updateFeatured()
  52. }
  53. super.update(q, post)
  54. }
  55. override def insert(post: Post) = {
  56. if (post.featured) {
  57. updateFeatured()
  58. }
  59. super.insert(post)
  60. }
  61. def updateFeatured() {
  62. collection.updateMulti(MongoDBObject("featured" -> true), $set("featured" -> false))
  63. }
  64. }