Created
July 29, 2011 04:05
-
-
Save xuwei-k/1113107 to your computer and use it in GitHub Desktop.
casbah dynamic DateTime and Regex support extension
This file contains hidden or 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
import com.mongodb.casbah.Imports._ | |
import com.mongodb.casbah.dynamic._ | |
import java.util.Date | |
import scala.util.matching.Regex | |
import java.util.regex.Pattern | |
import org.scala_tools.time.Imports._ | |
object DynamicMongo{ | |
implicit def dynamicConverter(obj:DBObject) | |
= new ToDynamic(obj) | |
class ToDynamic(obj:DBObject){ | |
def toDynamic:DynamicDBObject = new DynamicMongoObj( obj ) | |
} | |
class DynamicMongoObj(obj:DBObject = new BasicDBObject) extends DynamicDBObject(obj){ | |
override def defaultCaster: PartialFunction[Option[Any], MongoDynamic] = { | |
super.defaultCaster.orElse{ | |
case Some(d:Date) => ValueMongoDynamic(new DateTime(d)) | |
case Some(r:Pattern) => ValueMongoDynamic(new Regex(r.pattern)) | |
case Some(r:Regex) => ValueMongoDynamic(r) | |
} | |
} | |
} | |
} |
This file contains hidden or 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
import org.specs2.mutable._ | |
import DynamicMongo._ | |
import com.mongodb.casbah.Imports._ | |
import com.mongodb.casbah.dynamic._ | |
import org.scala_tools.time.Imports._ | |
import java.util.regex.Pattern | |
import scala.util.matching.Regex | |
class DynamicMongoSpec extends Specification { | |
"DynamicMongo" should { | |
"Date should be able to parse" in { | |
val d = new java.util.Date | |
val obj = DBObject("foo" -> d ).toDynamic | |
obj.foo.typed[DateTime] mustEqual Some(new DateTime(d)) | |
} | |
"java Pattern object should be able to parse" in { | |
val p = Pattern.compile("bar*") | |
val obj = DBObject("foo" -> p ).toDynamic | |
obj.foo.typed[Regex].map{_.pattern.pattern} mustEqual Some("bar*") | |
} | |
"scala Regex object should be able to parse" in { | |
val r = "baz*".r | |
val obj = DBObject("foo" -> p ).toDynamic | |
obj.foo.typed[Regex].map{_.pattern.pattern} mustEqual Some("baz*") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment