Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

- Added expand method to unpack dot notation in large embedded docs. No

  orElse version - just do expand("foo.bar.baz") orElse "foo" or such,
  you slacker.  Or use pattern matching.
  • Loading branch information...
commit 8305d639a189c168c5239a64b6c978338d59cddb 1 parent 35c1aa9
@bwmcadams bwmcadams authored
View
2  project/build.properties
@@ -3,7 +3,7 @@
project.organization=com.novus
project.name=casbah
sbt.version=0.7.4
-project.version=1.0.7.5
+project.version=1.0.8
def.scala.version=2.7.7
build.scala.versions=2.8.0
project.initialize=false
View
33 src/main/scala/mongodb/MongoDBObject.scala
@@ -29,6 +29,7 @@ import util.Logging
import com.mongodb._
+import scala.annotation.tailrec
import scala.collection.JavaConversions._
import scala.collection.generic._
import scala.collection.mutable.Map
@@ -70,6 +71,38 @@ trait MongoDBObject extends Map[String, AnyRef] with Logging {
}
}
+
+ /**
+ * Utility method to emulate javascript dot notation
+ * Designed to simplify the occasional insanity of working with nested objects.
+ * Your type parameter must be that of the item at the bottom of the tree you specify...
+ * If cast fails - it's your own fault.
+ */
+ def expand[A <% AnyRef : Manifest](key: String): Option[A] = {
+ require(manifest[A] != manifest[scala.Nothing], "Type inference failed; expand[A]() requires an explicit type argument (e.g. dbObject[<ReturnType](\"someKey\") ) to function correctly.")
+ @tailrec def _dot(dbObj: DBObject, key: String): Option[DBObject] =
+ if (key.indexOf('.') < 0) {
+ log.trace("_dot returning on key '%s'", key)
+ dbObj.getAs[DBObject](key)
+ }
+ else {
+ val (pfx, sfx) = key.splitAt(key.indexOf('.'))
+ log.trace("_dot recursing on pfx: '%s', sfx: '%s'", pfx, sfx)
+ dbObj.getAs[DBObject](pfx) match {
+ case Some(base) => _dot(base, sfx.stripPrefix("."))
+ case None => {
+ log.debug("Split key '%s' to '%s' & '%s' but found no value in object.", key, pfx, sfx.stripPrefix("."));
+ None
+ }
+ }
+ }
+
+ _dot(this, key) match {
+ case None => None
+ case Some(value) => Some(value.asInstanceOf[A])
+ }
+ }
+
def +=(kv: (String, AnyRef)) = {
put(kv._1, kv._2)
this
View
2  src/test/resources/casbah.config
@@ -1,5 +1,5 @@
log {
- level = "info"
+ level = "trace"
console = on
}
Please sign in to comment.
Something went wrong with that request. Please try again.