Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created August 1, 2014 10:17
Show Gist options
  • Save izmailoff/63e016da84b073cb24b9 to your computer and use it in GitHub Desktop.
Save izmailoff/63e016da84b073cb24b9 to your computer and use it in GitHub Desktop.
Example of MongoRecord and MongoMetaRecord without using singleton meta object
// This is an example of how one can use MongoRecord and it's `meta` object MongoMetaRecord without
// using regular Scala singleton object.
//
// This way you can set Mongo DB connection identifier for each meta object and have multiple
// meta objects available. Usually you would not want to do that unless you use multiple databases
// in the same application. My motivation was that Spray unit tests would run concurrently with Akka
// ActorSystem and regular Lift dependency injection would not work because it's scope is ThreadLocal.
//
// Some more details here:
// https://groups.google.com/forum/#!topic/liftweb/5NfI9DxQ99Q
package com.izmailoff
import com.izmailoff.common.db.connection.MongoConfig
import net.liftweb.mongodb.record.{MongoMetaRecord, MongoRecord}
import net.liftweb.mongodb.record.field.ObjectIdPk
import net.liftweb.record.field.IntField
import com.foursquare.rogue.LiftRogue._
// this has to be a class, not a trait
abstract class SomethingElse extends MongoRecord[SomethingElse] with ObjectIdPk[SomethingElse] {
object something extends IntField(this)
}
trait SomethingElseMeta extends SomethingElse with MongoMetaRecord[SomethingElse] {
self: MongoMetaRecord[SomethingElse] =>
override def meta = self
override protected def instantiateRecord: SomethingElse =
new SomethingElse {
override val meta = self
}
override def collectionName = "something"
}
object RunMe extends App {
// regular Mongo connection initialization
MongoConfig.init()
// create meta object:
val smthElse = new SomethingElseMeta {}
// save a few docs:
val rec1 = smthElse.createRecord
println("REC1 " + rec1 + " fields: " + rec1.fields())
val rec2 = rec1.something(1)
println("REC2 " + rec2 + " fields: " + rec2.fields())
val rec3 = rec2.save
println("REC3 " + rec3 + " fields: " + rec3.fields())
smthElse.createRecord.something(2).save
smthElse.createRecord.something(3).save
// test that find works as well
println(smthElse.findAll)
println(smthElse.where(_.something eqs 1).fetch())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment