diff --git a/src/main/scala/app/ControllerBase.scala b/src/main/scala/app/ControllerBase.scala index 7d88da8..b338f36 100644 --- a/src/main/scala/app/ControllerBase.scala +++ b/src/main/scala/app/ControllerBase.scala @@ -95,7 +95,23 @@ /** * Context object for the current request. */ -case class Context(path: String, loginAccount: Option[Account], currentUrl: String, request: HttpServletRequest) +case class Context(path: String, loginAccount: Option[Account], currentUrl: String, request: HttpServletRequest){ + + /** + * Get object from cache. + * + * If object has not been cached with the specified key then retrieves by given action. + * Cached object are available during a request. + */ + def cache[A](key: String)(action: => A): A = { + Option(request.getAttribute("cache." + key).asInstanceOf[A]).getOrElse { + val newObject = action + request.setAttribute("cache." + key, newObject) + newObject + } + } + +} /** * Base trait for controllers which manages account information. diff --git a/src/main/scala/view/helpers.scala b/src/main/scala/view/helpers.scala index 83d7ce8..1ef438e 100644 --- a/src/main/scala/view/helpers.scala +++ b/src/main/scala/view/helpers.scala @@ -81,11 +81,8 @@ * Looks up Gravatar if avatar icon has not been configured in user settings. */ def avatar(userName: String, size: Int, tooltip: Boolean = false)(implicit context: app.Context): Html = { - val account = Option(context.request.getAttribute("cache.account." + userName).asInstanceOf[model.Account]).orElse { - new AccountService {}.getAccountByUserName(userName).map { account => - context.request.setAttribute("cache.account." + userName, account) - account - } + val account = context.cache(s"account.${userName}"){ + new AccountService {}.getAccountByUserName(userName) } val src = account.collect { case account if(account.image.isEmpty) => s"""http://www.gravatar.com/avatar/${StringUtil.md5(account.mailAddress)}?s=${size}"""