Skip to content

Commit

Permalink
added ability to specify strategy for turning non-string Map keys int…
Browse files Browse the repository at this point in the history
…o strings
  • Loading branch information
maxaf committed Aug 28, 2010
1 parent e84738e commit 69629b9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
@@ -0,0 +1,14 @@
package com.novus.casbah.mapper.annotations.raw;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.novus.casbah.mapper.MapKeyStrategy;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface KeyStrategy {
Class value();
}
25 changes: 24 additions & 1 deletion casbah-mapper/src/main/scala/mapper/Mapper.scala
Expand Up @@ -132,6 +132,25 @@ class RichPropertyDescriptor(val idx: Int, val pd: PropertyDescriptor, val paren
case _ => false
}

lazy val mapKeyStrategy = annotation[KeyStrategy](pd, classOf[KeyStrategy]) match {
case Some(ann) => Some(ann.value.newInstance.asInstanceOf[MapKeyStrategy])
case _ => None
}

def mapKey(k: Any): String = {
k match {
case s: String if s != null && s != "" => s
case _ => mapKeyStrategy match {
case Some(strategy) => strategy.transform(k)
case _ => {
log.warning("%s: transforming non-string map key '%s' (%s) using toString",
this, k, (if (k == null) "NULL" else k.asInstanceOf[AnyRef].getClass))
"%s".format(k)
}
}
}
}

def readMapper(p: AnyRef) = {
log.trace("readMapper: %s -> %s, %s", p, Mapper(innerType.getName).isDefined, Mapper(p.getClass.getName).isDefined)
Mapper(innerType.getName) match {
Expand Down Expand Up @@ -272,7 +291,7 @@ abstract class Mapper[P <: AnyRef : Manifest]() extends Logging with OJ {
case b: Buffer[AnyRef] if prop.embedded_? => Some(b.map(embeddedPropValue(p, prop, _)))
case m if prop.map_? => Some(m.asInstanceOf[scala.collection.Map[String, Any]].map {
case (k, v) => {
k -> (if (prop.embedded_?) embeddedPropValue(p, prop, v.asInstanceOf[AnyRef])
prop.mapKey(k) -> (if (prop.embedded_?) embeddedPropValue(p, prop, v.asInstanceOf[AnyRef])
else v)
}
}.asDBObject)
Expand Down Expand Up @@ -479,3 +498,7 @@ private[mapper] sealed trait MapperDirection
private[mapper] case object ReadMapper extends MapperDirection
private[mapper] case object WriteMapper extends MapperDirection
class MissingMapper(d: MapperDirection, c: Class[_], m: String = "no further info") extends Exception("%s is missing for: %s (%s)".format(d, c, m))

trait MapKeyStrategy {
def transform(k: Any): String
}
1 change: 1 addition & 0 deletions casbah-mapper/src/main/scala/mapper/annotations.scala
Expand Up @@ -7,4 +7,5 @@ package object annotations {
type ID = raw.ID @getter
type Key = raw.Key @getter
type UseTypeHints = raw.UseTypeHints @getter
type KeyStrategy = raw.KeyStrategy @getter
}

0 comments on commit 69629b9

Please sign in to comment.