Skip to content

Instantly share code, notes, and snippets.

@tgpfeiffer
Created April 26, 2013 22:04
Show Gist options
  • Save tgpfeiffer/5470773 to your computer and use it in GitHub Desktop.
Save tgpfeiffer/5470773 to your computer and use it in GitHub Desktop.
Helper object to work around S.?(...) working only within a valid session in Lift.
package code
import java.util.{ResourceBundle, Locale}
import xml.{Node, NodeSeq}
import net.liftweb.util.Helpers.tryo
import net.liftweb.http.{Templates, LiftRules, S}
import net.liftweb.common._
import net.liftweb.util.{BundleBuilder, Helpers, NamedPF, Props}
object V extends Loggable {
var resourceBundles: Map[Locale, List[ResourceBundle]] = Map()
def ?(s: String, xs: Any*): String = tryo {
S.?(s, xs: _*)
} getOrElse ({
logger.error("error while looking up '" + s + "': not in session")
s
})
def ?(locale: Locale, str: String, xs: Any*): String = tryo {
val trans = S.session match {
case Full(sess) =>
S.?(str, locale)
case _ =>
def rawResBundle(loc: Locale): Box[ResourceBundle] = {
for {
xml <- Templates("_resources" :: Nil, loc)
bundle <- BundleBuilder.convert(xml, loc)
} yield bundle
}
val bundle = if (resourceBundles.isDefinedAt(locale)) {
// check if we have a bundle for the given locale
resourceBundles(locale)
} else {
// otherwise, look it up
val (lookupTime, bundles) = Helpers.calcTime({
rawResBundle(locale).toList
})
logger.debug("[" + lookupTime + "ms] looked up bundles: " + bundles)
resourceBundles += (locale -> bundles)
bundles
}
// look up the given translation key
val (translTime, trans) = Helpers.calcTime(bundle.flatMap(r => tryo(r.getObject(str) match {
case s: String => Full(s)
case n: Node => Full(n.text)
case ns: NodeSeq => Full(ns.text)
case _ => Empty
}).flatMap(s => s)).find(s => true) getOrElse {
LiftRules.localizationLookupFailureNotice.foreach(_(str, locale));
str
})
logger.debug("[" + translTime + "ms] translated " + str + " into locale " + locale + ": '" + trans + "'")
trans
}
val result = if (xs.length == 0)
trans
else
String.format(locale, trans, xs.flatMap {case s: AnyRef => List(s) case _ => Nil}.toArray: _*)
result
} getOrElse ({
logger.error("error while looking up '" + str + "': not in session")
str
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment